Getting information from the Moodle API as a student

一笑奈何 提交于 2019-12-02 01:33:05

If your university has enabled Web Services for the mobile app, you can generate your own API token and call the Web Services used by the mobile app. If the latter are not enabled, you have to get in touch with your administrator to get Web Services access.

Demo using moodle.org

First, let's get an API token (replace $PASSWORD with your password):

$ curl -d username="fmcorz" -d password="$PASSWORD" 'https://moodle.org/login/token.php?service=moodle_mobile_app'
{
  "token":"SNIPTOKEN",
  "privatetoken":"SNIPPRIVATE"
}

Next, we need your userid, it will be used throughout other web services call. You can obtain your userid by calling the web service core_webservice_get_site_info. Make sure to replace $TOKEN with the token you obtained above.

$ curl -d wstoken="$TOKEN" -d wsfunction=core_webservice_get_site_info 'https://moodle.org/webservice/rest/server.php?moodlewsrestformat=json' | python -m json.tool | grep userid
"userid": 1451616,

Now that you have your userid, we can request the courses that you are enrolled in.

$ curl -d wstoken="$TOKEN" -d wsfunction=core_enrol_get_users_courses -d userid=1451616 'https://moodle.org/webservice/rest/server.php?moodlewsrestformat=json' | python -m json.tool
[
    {
        ...snip...
        "fullname": "Moodle in English",
        "id": 5,
        ...snip...
    },
    {
        ...snip...
        "fullname": "Moodle en fran\u00e7ais",
        "id": 20,
        ...snip...
    },
    {
        ...snip...
        "fullname": "Moodle Certification",
        "id": 48,
        ...snip...
    }
]

Recap'

Pre-requisites:

  • The Mobile App webservices must be enabled
  • The REST protocol must be enabled
  • You need an API token

Querying:

  • Requests are made to YOURHOST/webservice/rest/server.php?moodlewsrestformat=json.
  • Requests must be POST requests
  • Requests must contain wstoken: Your token
  • Requests must contain wsfunction: The function you are calling
  • Requests type must be: application/x-www-form-urlencoded

More

I've greatly simplified how this works and what alternatives there are, but this should get you started. You will likely be interested in looking at the developer documentation to get more information about the available web services:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!