DEV Community

Lawrence Lagerlof
Lawrence Lagerlof

Posted on • Updated on

MoodleRest, a PHP class to query Moodle REST webservices

What it does, exactly?

MoodleRest allow you to easily make GET or POST requests to query or update information from many webservices available on Moodle.

"Moodle is a learning platform designed to provide educators, administrators and learners with a single robust, secure and integrated system to create personalised learning environments".

This lib can return information from Moodle webservices in one of these formats:

  • array
  • json
  • xml

The GitHub project page

This article covers the basics. Many more examples and other features on project page.


Ensure you already have access to a Moodle webservice. To use this class you will need a token (generated by Moodle admin) with the necessary capabilities for the services you want to access.

To the code

You have 2 options to add this lib to your project:

Option One

Use Composer to include it in your project.

  • Inside your project directory create or modify the file composer.json:
    "require": {
        "llagerlof/moodlerest": "2.3.0"
  • In the same directory of the composer.json, run:
$ composer install
  • In your project, load the lib using composer autoloader:
require_once dirname(__FILE__) . '/vendor/autoload.php';

Option Two

Just include the MoodleRest.php class directly in your script.

require_once dirname(__FILE__) . '/MoodleRest.php';

The MoodleRest constructor

You can pass 2 parameters:

  • A full url path to the Moodle webserver
  • The token generated by Moodle admin.


$MoodleRest = new MoodleRest(

The method request()

This method needs at least 2 parameters:

  • The webservice functiona name (string).
  • The parameters (array) passed to the webservice. The MoodleRest will internally convert this array to a query string. If you need to learn how to build an array compatible to each webservice's function I have you covered!

Query example (GET)

Query 2 Moodle groups with IDs 1 and 2, passing the server URL and token in constructor using the request method.

$MoodleRest = new MoodleRest(

$groups = $MoodleRest->request(
    array('groupids' => array(1,2))


Inserting data example (POST)

Set the server and token in constructor and make a request to create a group on Moodle.

$MoodleRest = new MoodleRest(

$new_group = array(
    'groups' => array(
            'courseid' => 2, 
            'name' => 'Group name', 
            'description' => 'Group description'

The default request's METHOD is to make a GET request, but you can change it to POST.
This is recommended when inserting and updating data.

$return = $MoodleRest->request(

// If you want the requested URL
echo $MoodleRest->getUrl();

That's it! Quick and easy.

More features and examples on project page.

Top comments (0)