Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Creating a web service client: Difference between revisions

From MoodleDocs
No edit summary
 
(53 intermediate revisions by 10 users not shown)
Line 1: Line 1:
{{Moodle_2.0}}
{{Moodle_2.0}}
[[Image:Moodle web service function documentation.jpg|thumb]]You need to have already setup a web service. You can get help from [[How to enable web services for ordinary users]] or [[How to enable web services for an external system]] . Then have a look to your [https://docs.moodle.org/en/How_to_get_a_security_key security keys] page. You'll find there your token and the web service documentation associated with this token.
[[Image:Moodle web service function documentation.jpg|thumb]]You need to know how to [https://docs.moodle.org/en/How_to_create_and_enable_a_web_service setup a web service] first.
To see the API Documentation, connect as Admin and go to '''Administration > Plugins > Web services > API Documentation'''
== Simple REST request example ==
To quickly test the web service works you can visit the end point from the browser or via curl. For example to call a function via REST protocol:
<syntaxhighlight lang="php">
$ curl "https://your.site.com/webservice/rest/server.php?wstoken=...&wsfunction=...&moodlewsrestformat=json"
</syntaxhighlight>
Customise the parameters <tt>wstoken</tt> and <tt>wsfunction</tt> to match the server side setup. Append additional parameters for the function call as needed with "&parameter_name=param", or if your parameter is an array then use "&array_name[index][parameter_name]=param". With the core_user_create_users function's (required) parameters for example:
<syntaxhighlight lang="php">
$ curl "...&moodlewsrestformat=json&wsfunction=core_user_create_users&moodlewsrestformat=json&users[0][username]=testuser&users[0][firstname]=Anne&users[0][lastname]=Example..."
</syntaxhighlight>
The <tt>moodlewsrestformat</tt> parameter affects the response format and can be either <tt>xml</tt> (default) or <tt>json</tt>.
== Officially supported protocols ==
; REST : The Moodle REST server accepts GET/POST parameters and return XML/JSON values. This server is not RESTfull.
; SOAP : The Moodle SOAP server is based on the Zend SOAP server (itself based on the PHP SOAP server). Zend publishes [http://framework.zend.com/manual/en/zend.soap.client.html a Zend SOAP client]. The current server implementation doesn't fully work with Java/.Net because we didn't generated a fully describe WSDL yet. If you are working on a Java/.Net client, follow or participate to the tracker issues MDL-28988 / MDL-28989
; XML-RPC : The Moodle XML-RPC server is based on Zend XML-RPC server. Zend also publishes [http://framework.zend.com/manual/en/zend.xmlrpc.client.html a Zend XML-RPC client].
; AMF (Versions < Moodle 3.0) : the Moodle AMF server is based on the Zend AMF server. The test client can be found in ''Settings blocks > Site Administration > Development > Web service test client > AMF Test client''.
== Demo client examples ==
Demo client sample codes can be downloaded on [https://github.com/moodlehq/sample-ws-clients Github].


= Officially supported protocols=
For HTML5 app creators, you can also find:
* a nice [https://github.com/jleyva/umm phonegap / Jquery mobile template]
* a proof of concept of [http://moodle.org/mod/forum/discuss.php?d=189882 javascript cross-domain with Sencha Touch 1.1]
Node.js apps can use the [https://github.com/mudrd8mz/node-moodle-client moodle-client] module.


* '''REST''': the Moodle REST server uses POST for parameters and XML for returned values. This server is not RESTfull.
A [http://moodle.org/mod/forum/discuss.php?d=199453 Java Library for REST] can be found on [http://sourceforge.net/projects/moodlerestjava/ Sourceforge].
* '''SOAP''': the Moodle SOAP server is based on the Zend SOAP server (itself based on the PHP SOAP server). Zend publishes [http://framework.zend.com/manual/en/zend.soap.client.html a Zend SOAP client]. The current server implementation doesn't work with Java/.Net because we didn't generated [http://geekandpoke.typepad.com/geekandpoke/2009/11/service-calling-made-easy-part-1.html a fully describe WSDL] yet. If you are working on a Java/.Net client, follow or participate to the tracker issue MDL-20804
* '''XML-RPC''': the Moodle XML-RPC server is based on Zend XML-RPC server. Zend also publishes [http://framework.zend.com/manual/en/zend.xmlrpc.client.html a Zend XML-RPC client].
* '''AMF''': the Moodle AMF server is based on the Zend AMF server. The test client can be found in ''Settings blocks > Site Administration > Development > Web service test client > AMF Test client''.


= PHP client examples =
A [https://github.com/llagerlof/MoodleRest PHP Library for REST] can be found on GitHub.
In all these client examples we will create two groups calling the web service function ''moodle_group_create_groups''.


== XML-RPC ==
A [https://github.com/zaddok/moodle Go Library for REST] can be found on GitHub.
The Moodle XML-RPC server extends Zend XML-RPC Server. It is recommended to have a look to the [http://framework.zend.com/manual/en/zend.xmlrpc.client.html Zend XML-RPC client documentation]


<code php>
A [https://github.com/smartcommunitylab/moodle_import Python Library for REST] can be found on GitHub.
 
== How to get a user token ==
//set two groups
{{Moodle_2.2}}
$group = new stdClass();
Your client can call the script located in /login/token.php with a simple HTTP request. We highly recommend to do it securely with HTTPS.
$group->courseid = $course->id;
The required parameters are:
$group->name = 'group1';
* username
$group->enrolmentkey = '';
* password
$group->description = 'Group 1';
* service shortname - The service shortname is usually hardcoded in the pre-build service (db/service.php files). Moodle administrator will be able to edit shortnames for service created on the fly: MDL-29807. If you want to use the Mobile service, its shortname is <tt>moodle_mobile_app</tt>. Also useful to know, the database shortname field can be found in the table named external_services.
$group2 = new stdClass();
Request:
$group2->courseid = $course->id;
<syntaxhighlight lang="php">
$group2->name = 'group2';
https://www.yourmoodle.com/login/token.php?username=USERNAME&password=PASSWORD&service=SERVICESHORTNAME
$group2->enrolmentkey = '';
</syntaxhighlight>
$group2->description = 'Group 2';
Response: (HTTP)
 
<syntaxhighlight lang="php">
//set web service parameters
{token:4ed876sd87g6d8f7g89fsg6987dfh78d}
$paramgroups = array($group, $group2);
</syntaxhighlight>
$params = array('groups' => $paramgroups);
Response: (HTTPS) - Since at least M3.9
 
<syntaxhighlight lang="php">
//set web service url server => token need to be passed in the url
{
$serverurl = $remotemoodleurl . "/webservice/xmlrpc/server.php" . '?wstoken=' . $token;
     "token": "9859148a89546f0efe716a58e340849b",
 
    "privatetoken": "8RpHJevJ42W7QN23OMkeYcdOYw3YfWgWGKsak7WB3Z88wcApSCVZ9TgY6M5fEO1m"
//create the xmlrpc client instance
require_once 'Zend/XmlRpc/Client.php';
$xmlrpcclient = new Zend_XmlRpc_Client($serverurl);
 
//make the web service call
$function = 'moodle_group_create_groups';
try {
     $createdgroups = $client->call($function, $params);
} catch (Exception $e) {
    var_dump($e);
}
}
</code>
</syntaxhighlight>
 
=== Difference between Moodle versions ===
== SOAP ==
* Moodle 2.2 and later: the script can generate user tokens for any service shortname (of course users must be allowed on the service, see [[:en:How to create and enable a web service|How to create and enable a web service]]).
The Moodle SOAP server extends Zend SOAP Server. It is recommended to have a look to the [http://framework.zend.com/manual/en/zend.soap.client.html Zend SOAP client documentation].
* Moodle 2.1: the script can only generate tokens for the official built-in mobile service. However the script can returns tokens for other services, they just need to have been previously generated.
Except the class name ''Zend_Soap_Client'', the entire example code would be similar to XML-RPC.
=== About service shortname ===
 
At the moment a service can have a shortname if you:
== REST ==
* create the service as a built-in service (in db/services.php files)
Look at the web service function documentation on your [https://docs.moodle.org/en/How_to_get_a_security_key security keys] page to know about the returned XML structure.
* add the shortname manually in the DB. Note: we'll add the admin UI for shortname later (MDL-30229)
 
== Text formats ==
<code php>
=== Moodle 2.0 to 2.2 ===
//get the profile data of Moodle User
{{Moodle_2.0}}
 
HTML is the format sent/received by web service functions. All returned file urls are converted to 'http://xxxx/webservice/pluginfile.php/yyyyyyyy'
include 'Zend/Loader/Autoloader.php';
=== Moodle 2.3 and later ===
Zend_Loader_Autoloader::autoload('Zend_Loader');
{{Moodle_2.3}}
 
Since Moodle 2.3 you can add few GET/POST parameters to your request (for devs who have a good knowledge of File API and format_text()):
$params = array(
* ''moodlewssettingraw'' => false by default. If true, the function will not apply format_text() to description/summary/textarea. The function will return the raw content from the DB.
    'userids' => array(2,4), // the params to passed to the function
* ''moodlewssettingfileurl'' => true by default, returned file urls are converted to 'http://xxxx/webservice/pluginfile.php/yyyyyyyy'. If false the raw file url content from the DB is returned (e.g. @@PLUGINFILE@@)
    'wsfunction' => 'moodle_user_get_users_by_id',   // the function to be called
* ''moodlewssettingfilter'' => false by default. If true, the function will filter during format_text()
    'wstoken' => '8dc8f5ca046129706c0d85a56efcaddd' //token need to be passed in the url
=== Moodle 3.5 and later ===
);
{{Moodle_3.5}}
 
* ''moodlewssettinglang'' => to force a session language for when retrieving information (same behaviour than using the language selector in the site)
//set web service url server
== See also ==
$serverurl = "http://{servername}/webservice/rest/server.php";
* [[Web services|Web services developer documentation]]
 
* [[:en:Web_services|Web services user documentation]]
$client = new Zend_Http_Client($serverurl);
* [[Creating a web service and a web service function | Implement a web service and a web service function]]
 
* [[Web_services_Roadmap|Web service Roadmap]]
print "<pre>";
* [https://moodle.org/plugins/webservice_restful A RESTful webservice plugin] by Catalyst Moodle partner.
try {
    $client->setParameterPost($params);   
    $response = $client->request('POST');
 
    var_dump ($response);
} catch (exception $exception) {
    var_dump ($exception);
}
print "</pre>";
 
 
 
 
</code>
 
 
[[Category:Web Services]]
[[Category:Web Services]]

Latest revision as of 16:15, 7 February 2022

Moodle 2.0


Moodle web service function documentation.jpg

You need to know how to setup a web service first.

To see the API Documentation, connect as Admin and go to Administration > Plugins > Web services > API Documentation

Simple REST request example

To quickly test the web service works you can visit the end point from the browser or via curl. For example to call a function via REST protocol:

$ curl "https://your.site.com/webservice/rest/server.php?wstoken=...&wsfunction=...&moodlewsrestformat=json"

Customise the parameters wstoken and wsfunction to match the server side setup. Append additional parameters for the function call as needed with "&parameter_name=param", or if your parameter is an array then use "&array_name[index][parameter_name]=param". With the core_user_create_users function's (required) parameters for example:

$ curl "...&moodlewsrestformat=json&wsfunction=core_user_create_users&moodlewsrestformat=json&users[0][username]=testuser&users[0][firstname]=Anne&users[0][lastname]=Example..."

The moodlewsrestformat parameter affects the response format and can be either xml (default) or json.

Officially supported protocols

REST
The Moodle REST server accepts GET/POST parameters and return XML/JSON values. This server is not RESTfull.
SOAP
The Moodle SOAP server is based on the Zend SOAP server (itself based on the PHP SOAP server). Zend publishes a Zend SOAP client. The current server implementation doesn't fully work with Java/.Net because we didn't generated a fully describe WSDL yet. If you are working on a Java/.Net client, follow or participate to the tracker issues MDL-28988 / MDL-28989
XML-RPC
The Moodle XML-RPC server is based on Zend XML-RPC server. Zend also publishes a Zend XML-RPC client.
AMF (Versions < Moodle 3.0)
the Moodle AMF server is based on the Zend AMF server. The test client can be found in Settings blocks > Site Administration > Development > Web service test client > AMF Test client.

Demo client examples

Demo client sample codes can be downloaded on Github.

For HTML5 app creators, you can also find:

Node.js apps can use the moodle-client module.

A Java Library for REST can be found on Sourceforge.

A PHP Library for REST can be found on GitHub.

A Go Library for REST can be found on GitHub.

A Python Library for REST can be found on GitHub.

How to get a user token

Moodle 2.2

Your client can call the script located in /login/token.php with a simple HTTP request. We highly recommend to do it securely with HTTPS. The required parameters are:

  • username
  • password
  • service shortname - The service shortname is usually hardcoded in the pre-build service (db/service.php files). Moodle administrator will be able to edit shortnames for service created on the fly: MDL-29807. If you want to use the Mobile service, its shortname is moodle_mobile_app. Also useful to know, the database shortname field can be found in the table named external_services.

Request:

https://www.yourmoodle.com/login/token.php?username=USERNAME&password=PASSWORD&service=SERVICESHORTNAME

Response: (HTTP)

{token:4ed876sd87g6d8f7g89fsg6987dfh78d}

Response: (HTTPS) - Since at least M3.9

{
    "token": "9859148a89546f0efe716a58e340849b",
    "privatetoken": "8RpHJevJ42W7QN23OMkeYcdOYw3YfWgWGKsak7WB3Z88wcApSCVZ9TgY6M5fEO1m"
}

Difference between Moodle versions

  • Moodle 2.2 and later: the script can generate user tokens for any service shortname (of course users must be allowed on the service, see How to create and enable a web service).
  • Moodle 2.1: the script can only generate tokens for the official built-in mobile service. However the script can returns tokens for other services, they just need to have been previously generated.

About service shortname

At the moment a service can have a shortname if you:

  • create the service as a built-in service (in db/services.php files)
  • add the shortname manually in the DB. Note: we'll add the admin UI for shortname later (MDL-30229)

Text formats

Moodle 2.0 to 2.2

Moodle 2.0


HTML is the format sent/received by web service functions. All returned file urls are converted to 'http://xxxx/webservice/pluginfile.php/yyyyyyyy'

Moodle 2.3 and later

Moodle 2.3

Since Moodle 2.3 you can add few GET/POST parameters to your request (for devs who have a good knowledge of File API and format_text()):

  • moodlewssettingraw => false by default. If true, the function will not apply format_text() to description/summary/textarea. The function will return the raw content from the DB.
  • moodlewssettingfileurl => true by default, returned file urls are converted to 'http://xxxx/webservice/pluginfile.php/yyyyyyyy'. If false the raw file url content from the DB is returned (e.g. @@PLUGINFILE@@)
  • moodlewssettingfilter => false by default. If true, the function will filter during format_text()

Moodle 3.5 and later

Moodle 3.5

  • moodlewssettinglang => to force a session language for when retrieving information (same behaviour than using the language selector in the site)

See also