LMSouq
moodle-core Open

Accessing a Moodle server's API via Python's request library

GR
grhmstl
1 month ago
3 views
Problem Description
I'm trying to access the web services of a Moodle installation I have using Python's requests library. I have the API's documentation and an example project written in php (I haven't looked at php before and is way more difficult than I would expect for me to understand) but am really struggling to properly format the request. The site is returning invalid paramater detected so I'm pretty sure my endpoint, authorization token, and server config is working and it's just the format of the data that is letting me down. First here is the error... <?xml version="1.0" encoding="UTF-8" ?> <EXCEPTION class="invalid_parameter_exception"> <ERRORCODE>invalidparameter</ERRORCODE> <MESSAGE>Invalid parameter value detected</MESSAGE> </EXCEPTION> And now my code... import requests target = 'http://example.com/moodle/webservice/rest/server.php?' moodle_create_token = 'xxx' moodle_enrol_token = 'yyy' url_payload = { "wstoken":moodle_create_token, "wsfunction":"core_user_create_users" } ###not sure if I should just be passing this as a dict or some deeper more layered struct payload = { "username":"testuser", "password":'testpass', "firstname":'testf', "lastname":'testl', "email":"test@example.com", "idnumber":"1234" } ###not sure how to include the payload as the last argument in the function (currently data=) ###I feel like at this point I've just been throwing random data at it and hoping something sticks haha. r=requests.post(target, params=url_payload, data=payload) Here is the site's documentation [moodle api general structure][1] [moodle api XML-RPC (PHP structure)][2] [moodle api REST (POST parameters)][3] [moodle response format 1][4] [moodle response format 2][5] Finally the example in php. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>V6</title> </head> <body> <?php //load curl.php require_once('curl.php'); function randomPassword() //according to Moodle password requirements { $part1 = ""; $part2 = ""; $part3 = ""; //alphanumeric LOWER $alphabet = "abcdefghijklmnopqrstuwxyz"; $password_created = array(...

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base