Skip to content

Instantly share code, notes, and snippets.

@phette23
Created May 3, 2019 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phette23/f0289c3d9883b6e94e4a5308341459e4 to your computer and use it in GitHub Desktop.
Save phette23/f0289c3d9883b6e94e4a5308341459e4 to your computer and use it in GitHub Desktop.
get Moodle course category information from API
import requests
# request URL looks like
# https://moodle.cca.edu/webservice/rest/server.php?wstoken=...&wsfunction=core_course_get_categories&moodlewsrestformat=json&criteria[0][key]=name&criteria[0][value]=2019SP
def get_mdl_categories(filter):
""" obtain a list of JSON representations of Moodle course categories
returns an array of category dicts (see their fields below)
`filter` is a dict like {"name": "Spring 2019"} which is used to retrieve only
categories where the given field matches the value. So, for instance, we can
find the term-level category by filtering on name and then find the children
of that term by filter on {"parent": {{id of term}} }. You may specify
multiple keys to filter upon.
fields are: id, name, parent, coursecount, visible, timemodified, depth, path*
* `path` looks like /{{parent ID}}/{{category ID}} so it's an effective way
to find where a category lies in the hierarchy. Thie list above is only the
useful fields. To see the full set, look at a returned value. A few fields
are empty or unused like "idnumber" and "description".
"""
# constants
url = 'https://moodle.cca.edu/webservice/rest/server.php'
# this token must be for an account with access to a service that includes the core_course_get_categories function
# all that gibberish can be found under the Moodle > Admin > Web Services pages
token = '...'
service = 'core_course_get_categories'
data_format = 'json'
params = {
'wstoken': token,
'wsfunction': service,
'moodlewsrestformat': data_format,
}
# construct criteria in PHP array query string format
# because it wouldn't be Moodle without a weird, antiquated nuance
num_filters = 0
for key, value in filter.items():
params["criteria[{}][key]".format(num_filters)] = key
params["criteria[{}][value]".format(num_filters)] = value
num_filters += 1
response = requests.get(url, params=params)
return response.json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment