Skip to content
Yannick Warnier edited this page Jun 6, 2023 · 98 revisions

REST Web Services

This is a non-exhaustive list of available web services using the REST protocol. If you want the exact list, check the main/webservices/api/v2.php script. Constants of the Rest class are defined in the class itself at main/inc/lib/webservices/Rest.php

Naming convention

  • All service names are split in "lower camelcase", like so: "get_user_api_key
  • All service names must include an action name (get/add/delete/authenticate/..)
  • All getters start with "get_"
  • All setters (addition) start with "add_" or "update_". Exceptions below were created before this convention was established
  • All deleters start with "delete_"

Calling procedure

You are expected to format your requests using JSON encode on a hash (called 'hash') containing the following array of parameters at a minimum:

Key Value
action The service function you are calling
username The username of the user, as defined by Chamilo
api_key A secret key specific to that user (the first time, you must generate this key by calling the "authenticate" action with a username and a *password*
course (optional) The internal ID of the course
session (optional) The internal ID of the session
other Whatever that specific action requires as additional parameter

Let it be noted, however, that additional parameters are usually sent directly as POST parameters rather than inside the REQUEST['hash']. We indicate below whenever a parameter has to be sent specifically through a particular HTTP method.

Responses

Responses are sent in a JSON encoded array (with the PHP option "JSON_PRETTY_PRINT"). If an error occured, the array will generally contain an 'error' entry set to true, and a 'message' entry containing the error message (not an error code) sent in the default platform language. If the call could be processed without error, then a 'data' entry containing another array of data is returned.

Notes on usernames

From 1.11.20 onward, you can enable the configuration setting webservice_return_user_field which will allow you to specify which extra field of the user you would like to return instead of its real username.

Experimental services

Some services have been marked as experimental. These work, but we don't recommend their use as their name and some of their parameters might still change in the future (to improve understandability and/or security).

Existing web services

Table of contents

authenticate

This is the first service to be called when using Chamilo REST Web Services, as you need an api_key for the other services. Call:

Key Value
action authenticate
username The username of the user launching the service (whom has the necessary permissions). Usually, that's you, i.e. jperry
password Your password

Response:

Key Value
url The official URL of the Chamilo installation, just in case (for subsequent calls)
apiKey The API key you will need for later calls. We're sorry we didn't name it api_key. It should have been.
gcmSenderId For mobile app notifications. Ignore if not on a mobile app.
{
  "error": false,
  "data": {
    "url": "http://YOURCHAMILO/",
    "apiKey": "{api_key}",
    "gcmSenderId": null
  }
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=authenticate' \
--form 'username={USERNAME}' \
--form 'password={PASSWORD}'

Code example in PHP:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @throws Exception
 *
 * @return string
 */
function authenticate() {
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : ' . $response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : ' . $jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

$apiKey = authenticate();
echo 'user API Key: '.$apiKey;

gcm_id

Google Cloud Messaging was the name of the Google service allowing for notifications to be sent to the user's mobile app. Send your GCM registration ID to save it in Chamilo. This is only useful for mobile devices and should be ignored otherwise.

Call:

Key Value
action gcm_id
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
registration_id

Response:

Key Value
status true

user_messages

Get the internal messages received on the platform (as the current user)

Call:

Key Value
action user_messages
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
last (POST) The ID of the last user message that was read. Defaults to 0 to start from the first message.

Response:

Key Value
data An array of messages details. See corresponding code
{
  "error": false,
  "data": []
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=user_messages' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}'

Code example in PHP:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
        ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getUserMessages($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
        ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'user_messages',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content,true);

    if ($jsonResponse['error']) {
        throw new Exception('Can not get user_messages : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Read user mesages
$userMessages = getUserMessages($apiKey);
echo json_encode($userMessages);

user_message_read

Mark a specific message (in the social network interface) as read.

Call:

Key Value
action user_message_read
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
messages (POST) A list of IDs for the messages to update

Response:

Key Value
data An array indexed on message ID with the status of the change (boolean true on success, false on failure)
{
  "error": false,
  "data": {
    "1": false,
    "2": false
  }
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
   --form 'action=user_message_read' \
   --form 'username={USERNAME}' \
   --form 'api_key={api_key}' \
   --form 'messages[]=1' \
   --form 'messages[]=2'

Code example in PHP:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getUserMessageRead($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'user_message_read',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'messages' => [
                    1,
                    2,
                    3
                ]
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('Can not get user_messages_read : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Mark a specific message (in the social network interface) as read.
$userMessagesRead = getUserMessageRead($apiKey);
echo json_encode($userMessagesRead);

user_message_unread

Mark a specific message (in the social network interface) as "unread".

Call:

Key Value
action user_message_unread
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
messages (POST) A list of IDs for the messages to update

Response:

Key Value
data An array indexed on message ID with the status of the change (boolean true on success, false on failure)
{
  "error": false,
  "data": {
    "1": false,
    "2": false
  }
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=user_message_unread' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'messages[]=1' \
--form 'messages[]=2'

Code example in PHP:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getUserMessageUnread($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'user_message_unread',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'messages' => [
                    1,
                    2,
                    3
                ]
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('Can not get user_messages_unread : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Mark a specific message (in the social network interface) as "unread".
$userMessagesUnread = getUserMessageUnread($apiKey);
echo json_encode($userMessagesUnread);

user_courses

Get a list of courses of the user calling this service.

Call:

Key Value
action user_courses
username Your username, i.e. jperry
user_id Optional search the user id instead by username
api_key The apiKey you received from the call to authenticate

Response:

Key Value
data An array of courses. See corresponding code
{
  "error": false,
  "data": [
    {
      "id": 1,
      "title": "Course Tittle",
      "code": "COURSE_CODE",
      "directory": "CourseDirectory",
      "urlPicture": "http://YOURCHAMILO/main/img/session_default.png",
      "teachers": "Teacher",
      "isSpecial": false
    }
  ]
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=user_courses' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}'

Code example in PHP:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getUserCourses($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'user_courses',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('Can not make user_courses : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get a list of courses of the user calling this service.
$userCourses = getUserCourses($apiKey);
echo json_encode($userCourses);

user_courses_by_dates

Get a list of courses of the user between two dates. Returns a list of courses, visible tests and taken tests.

Call:

Key Value
action user_courses_by_dates
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
user_id The ID of the user whose courses will be searched
start_date The date from which to start looking (YYYY-MM-DD format)
end_date The date until which to look (YYYY-MM-DD format)

Response:

Key Value
data An array of courses. See corresponding code
{
  "error": false,
  "data": [
   {
      "course_code":"BIGUPLOAD002",
      "course_title":"BIGUPLOAD 002",
      "visible_tests":[
         {
            "0":"quiz001",
            "1":0,
            "id":"83",
            "url":"http:\/\/my.chamilo118.com\/main\/exercise\/overview.php?cidReq=BIGUPLOAD002&id_session=0&gidReq=0&&exerciseId=83",
            "name":"quiz001"
         },
         {
            "0":"quiz002",
            "1":0,
            "id":"84",
            "url":"http:\/\/my.chamilo118.com\/main\/exercise\/overview.php?cidReq=BIGUPLOAD002&id_session=0&gidReq=0&&exerciseId=84",
            "name":"quiz002"
         }
      ],
      "taken_tests":[
         
      ]
   },
   {
      "course_code":"BIGUPLOAD003",
      "course_title":"BIGUPLOAD003",
      "visible_tests":[
         {
            "0":"quiz001",
            "1":0,
            "id":"79",
            "url":"http:\/\/my.chamilo118.com\/main\/exercise\/overview.php?cidReq=BIGUPLOAD003&id_session=0&gidReq=0&&exerciseId=79",
            "name":"quiz001"
         }
      ],
      "taken_tests":[
         
      ]
   }
  ]
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=user_courses_by_dates' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'user_id=70' \
--form 'start_date=2011-01-01' \
--form 'end_date=2022-10-07'

users_profiles_by_extra_field

Get the (filtered) list of users from an extra field value. Only returns a list of users who have that extra field set to the given value.

Call:

Key Value
action users_profiles_by_extra_field
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
field_name Your extra field variable
field_value Your extra field value
active Optional: Filter only active users (1) or get all users (0 or ignore this parameter) (only available since 1.11.20)

Response:

Key Value
data An array of users (pictureUri, id, status, fullName, username, officialCode, phone).
{
  "error": false,
  "data": [
    {
       "1":{
          "pictureUri":"http:\/\/{CHAMILO_ URL}\/main\/img\/unknown.jpg",
          "id":70,
          "status":5,
          "fullName":"test student",
          "username":"studenttest",
          "officialCode":"",
          "phone":""
       },
       "2":{
          "pictureUri":"http:\/\/{CHAMILO_ URL}\/main\/img\/unknown.jpg",
          "id":88,
          "status":5,
          "fullName":"Carlos Flores",
          "username":"student03",
          "officialCode":"",
          "phone":""
       }
    }
  ]
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=users_profiles_by_extra_field' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'field_name=proyecto' \
--form 'field_value=001'

courses_details_by_extra_field

Get the list of courses from extra field included count of visible exercises. Returns a list of courses.

Call:

Key Value
action courses_details_by_extra_field
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
field_name Your extra field variable
field_value Your extra field value

Response:

Key Value
data An array of courses include the count of visible exercises. See corresponding code
{
"error": false,
"data": [
 {
   "24":{
      "id":"AVANCEDELECCIONNOGUARDADA",
      "real_id":"24",
      "code":"AVANCEDELECCIONNOGUARDADA",
      "name":"CURSO 02 - PROYECTO 001",
      "title":"CURSO 02 - PROYECTO 001",
      "official_code":"AVANCEDELECCIONNOGUARDADA",
      "visual_code":"AVANCEDELECCIONNOGUARDADA",
      "sysCode":"AVANCEDELECCIONNOGUARDADA",
      "path":"AVANCEDELECCIONNOGUARDADA",
      "directory":"AVANCEDELECCIONNOGUARDADA",
      "creation_date":"2021-10-18 19:17:48",
      "titular":null,
      "tutor_name":null,
      "language":"english",
      "extLink":{
         "url":"http:\/\/",
         "name":""
      },
      "categoryCode":null,
      "category_code":null,
      "categoryName":null,
      "visibility":"2",
      "subscribe_allowed":"1",
      "subscribe":"1",
      "unsubscribe":"0",
      "course_language":"english",
      "activate_legal":false,
      "legal":null,
      "show_score":"1",
      "department_name":"",
      "department_url":"http:\/\/",
      "registration_code":null,
      "disk_quota":"100034150",
      "course_public_url":"http:\/\/{YOUR_CHAMILO}\/courses\/AVANCEDELECCIONNOGUARDADA\/index.php",
      "course_sys_path":"\/var\/www\/{YOUR_CHAMILO}\/app\/courses\/AVANCEDELECCIONNOGUARDADA\/",
      "add_teachers_to_sessions_courses":"0",
      "course_image_source":"",
      "course_image":"http:\/\/{YOUR_CHAMILO}\/main\/img\/icons\/48\/course.png",
      "course_image_large_source":"",
      "course_image_large":"http:\/\/{YOUR_CHAMILO}\/main\/img\/session_default.png",
      "count_visible_tests":0
   },
   "70":{
      "id":"BIGUPLOAD002",
      "real_id":"70",
      "code":"BIGUPLOAD002",
      "name":"BIGUPLOAD 002",
      "title":"BIGUPLOAD 002",
      "official_code":"BIGUPLOAD002",
      "visual_code":"BIGUPLOAD002",
      "sysCode":"BIGUPLOAD002",
      "path":"BIGUPLOAD002",
      "directory":"BIGUPLOAD002",
      "creation_date":"2022-04-05 17:26:10",
      "titular":null,
      "tutor_name":null,
      "language":"english",
      "extLink":{
         "url":"http:\/\/",
         "name":""
      },
      "categoryCode":null,
      "category_code":null,
      "categoryName":null,
      "visibility":"2",
      "subscribe_allowed":"1",
      "subscribe":"1",
      "unsubscribe":"0",
      "course_language":"english",
      "activate_legal":false,
      "legal":null,
      "show_score":"1",
      "department_name":"",
      "department_url":"http:\/\/",
      "registration_code":null,
      "disk_quota":"100034150",
      "course_public_url":"http:\/\/{YOUR_CHAMILO}\/courses\/BIGUPLOAD002\/index.php",
      "course_sys_path":"\/var\/www\/{YOUR_CHAMILO}\/app\/courses\/BIGUPLOAD002\/",
      "add_teachers_to_sessions_courses":"0",
      "course_image_source":"",
      "course_image":"http:\/\/{YOUR_CHAMILO}\/main\/img\/icons\/48\/course.png",
      "course_image_large_source":"",
      "course_image_large":"http:\/\/{YOUR_CHAMILO}\/main\/img\/session_default.png",
      "count_visible_tests":2
   },
 }
]
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=courses_details_by_extra_field' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'user_id=71' \
--form 'field_name=proyecto' \
--form 'field_value=001'

get_users_api_keys

Get all api keys for this webservice from all user in platform. It requires to be enabled by a configuration setting in configuration.php file.

$_configuration['webservice_enable_adminonly_api'] = true;

Request:

Key Value
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate.
action `get_users_api_keys'
page (Optional) Current position in pagination. Default is 1.
per_page (Optional) Number of items per page. Default is 30.
force (Optional) Force generation of apiKey when users has no one.
url_id (Optional) URL id to filter by. Default is null.

Example

curl --location 'https://{CHAMILO_ URL}/main/webservices/api/v2.php?api_key={API_KEY}&username={USERNAME}&action=get_users_api_keys'

Successful response:

Key Value
error false
data An array of paginated results
Key Value
total Total number of items
list An array of items
length Number of items in the current page
next (Optional) URL to the next page
Key Value
id The user id
username The user username
api_key The user api key

Example

{
    "error": false,
    "data": {
        "total": 68,
        "list": [
            {
                "id": "1",
                "username": "admin",
                "api_key": "dc5be67b57217631d9a0da9af6f4fab5"
            },
            {
                "id": "30",
                "username": "jcotton",
                "api_key": null
            }
        ],
        "length": 30,
        "next": "\/main\/webservices\/api\/v2.php?api_key=dc5be67b57217631d9a0da9af6f4fab5&username=admin&page=2&per_page=30"
    }
}

get_user_api_key

Get the api key for a specific user. It requires to be enabled by a configuration setting in configuration.php file.

$_configuration['webservice_enable_adminonly_api'] = true;

Request:

Key Value
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate.
action `get_user_api_key'
user The user username to get the api key for.
force (Optional) Force generation of apiKey when user has no one.
curl --location 'https://{CHAMILO_ URL}/main/webservices/api/v2.php?api_key={API_KEY}&username={USERNAME}&action=get_user_api_key&user=fapple'

Successful response:

Key Value
error false
data An array of results
Key Value
id The user id
username The user username
api_key The user api key

Example

{
    "error": false,
    "data": {
        "id": "6",
        "username": "fapple",
        "api_key": "fe5be67b12345671d9a0da9af6f4fcd5"
    }
}

view_my_courses

It allows the user to view his courses list in "My Courses" page .

Request

Method: GET

Key Value
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate.
action `view_my_courses'

Response

302 Redirect.

course_info

Get information about one course in particular

Call:

Key Value
action course_info
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course The internal course ID of a course in Chamilo (which you can get through user_courses, for example)
session Optional: the internal ID of the session from which we want the info (the available tools, mainly)

Response:

Key Value
data An array of courses information. See corresponding code
{
  "error": false,
  "data": {
    "id": 1,
    "title": "English for beginners",
    "code": "ENGLISH101",
    "directory": "ENGLISH101",
    "urlPicture": null,
    "teachers": "TEACHER",
    "tools": [
      {
        "type": "course_description"
      },
      {
        "type": "calendar_event"
      },
      {
        "type": "document"
      },
      {
        "type": "learnpath"
      },
      {
        "type": "link"
      },
      {
        "type": "quiz"
      },
      {
        "type": "announcement"
      },
      {
        "type": "forum"
      },
      {
        "type": "dropbox"
      },
      {
        "type": "user"
      },
      {
        "type": "group"
      },
      {
        "type": "chat"
      },
      {
        "type": "student_publication"
      },
      {
        "type": "survey"
      },
      {
        "type": "wiki"
      },
      {
        "type": "gradebook"
      },
      {
        "type": "glossary"
      },
      {
        "type": "notebook"
      }
    ]
  }
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_info' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'course=1'

Code example in PHP:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getCourseInfo($apiKey, $courseId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_info',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('Can not make course_info : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get information about one course in particular
$courseInfo = getCourseInfo($apiKey,1);
echo json_encode($courseInfo);

course_descriptions

Get descriptions for a given course (from the "course description" tool). This service is not "session-aware" at this time.

Call:

Key Value
action course_descriptions
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
fields Optional array of extra fields names. If the given extra fields exist for the course in which this description lies, it will return the value for the course, or an empty string if the field exist but it has no value for this course.

Response:

Key Value
data An array of course descriptions. See corresponding code

Example output (with a "client" extra field on the course):

{
  "error": false,
  "data": [
    {
      "id": "1",
      "title": "General description",
      "content": "<p>This is a great course, you should definitely subscribe!</p>\r\n",
      "extra_client": "ZARA"
    }
  ]
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_descriptions' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'course=1'

Code example in PHP:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getCourseDescription($apiKey, $courseId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_descriptions',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('Can not make course_descriptions : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get the list of documents in the given course.
$courseDescription = getCourseDescription($apiKey,1);
echo json_encode($courseDescription);

course_documents

Get the list of documents in the given course.

Call:

Key Value
action course_documents
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session from which we want the documents
dir_id (POST) Optional: an ID of a specific directory to filter those documents

Response:

Key Value
data An array of documents information. See corresponding code
{
  "error": false,
  "data": []
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_documents' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'course=1'

Php Example:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getCourseDocuments($apiKey, $courseId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_documents',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get course documents because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get the list of documents in the given course.
$courseDescription = getCourseDocuments($apiKey,1);
echo json_encode($courseDescription);

course_announcements

Get the announcements published in the given course.

Call:

Key Value
action course_announcements
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session from which we want the documents

Response:

Key Value
data An array of announcements. See corresponding code
{
  "error": false,
  "data": []
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_announcements' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'course=1'

Code example in PHP:

<?php

course_announcement

Get one specific course announcement

Call:

Key Value
action course_announcement
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session
announcement (POST) Internal ID of the announcement

Response:

Key Value
data An array of information about the announcement. See corresponding code

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_announcement' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'course=1' \
--form 'announcement=1'

Code example in PHP:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getCourseAnnouncement($apiKey, $courseId, $announcementId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_announcement',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId,
                'announcement ' => $announcementId,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('Can not make course_announcement : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get one specific course announcement
$courseAnnouncement = getCourseAnnouncement($apiKey,1,1);
echo json_encode($courseAnnouncement);

course_agenda

Get the list of calendar events from inside the given course.

Call:

Key Value
action course_agenda
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session

Response:

Key Value
data An array of events. See corresponding code
{
  "error": false,
  "data": []
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_agenda' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'course=1' 

Php Example:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';
/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getCourseAgenda($apiKey, $courseId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_agenda',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get course agenda because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get the list of calendar events from inside the given course.
$courseAgenda = getCourseAgenda($apiKey,1);
echo json_encode($courseAgenda);
 

course_notebooks

Call:

Key Value
action course_notebooks
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session

Response:

Key Value
data An array of notebooks. See corresponding code

course_forumcategories

Call:

Key Value
action course_forumcategories
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session

Response:

Key Value
data A list of forum categories. See corresponding code

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_forumcategories' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}'   \
--form 'course={courseId}' 

Php Example:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 * @param $courseId
 *
 * @return array
 * @throws Exception
 */
function getCourseForumCategories($apiKey, $courseId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_forumcategories',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get course documents because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//A list of forum categories
$courseForumCategories = getCourseForumCategories($apiKey,1);
echo json_encode($courseForumCategories);

course_forum

Get details about a specific forum.

Call:

Key Value
action course_forum
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session
forum (POST) The ID of a specific forum in the course

Response:

Key Value
data A mixed array with information about the forum and its threads. See corresponding code and following lines

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_forum' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}'   \
--form 'course={courseId}'   \
--form 'forum={forumId}'     

Php Example:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 * @param $courseId
 * @param $forumId
 *
 * @return array
 * @throws Exception
 */
function getCourseForum($apiKey, $courseId, $forumId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_forum',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId,
                'forum' => $forumId,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get course documents because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get details about a specific forum.
$courseForum = getCourseForum($apiKey,1,1);
echo json_encode($courseForum);

course_forumthread

Get details about a specific forum thread.

Call:

Key Value
action course_forumthread
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session
forum (POST) The internal ID of the forum
thread (POST) The internal ID of the thread

Response:

Key Value
data A mixed array with information about the thread and a list of posts inside that thread. See corresponding code and following lines

/**

  • @param $apiKey
  • @return int
  • @throws Exception

*/

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_forumthread' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'course={courseId}' \
--form 'forum={forumId}' \
--form 'forum={forumId}' \
--form 'thread={threadId}'

Php Example:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 * @param $courseId
 * @param $threadId
 *
 * @return array
 * @throws Exception
 */
function getCourseForumThread($apiKey, $courseId,$forumId,$threadId)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'course_forumthread',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'course' => $courseId,
                'forum' => $forumId,
                'thread' => $threadId,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get course documents because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get details about a specific forum thread.
$courseForumThread = getCourseForumThread($apiKey,1,1,1);
echo json_encode($courseForumThread);

course_exercises

Call:

Key Value
action course_exercises
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session
fields Optional array of extra field names. If provided, the service will return the values for the given fields in an item called "extra_" and the name of the field. Note that this will first search for that extra field in the exercise, but if not found, it will also look for that extra field in the course (in which the exercise is found).

Response:

Key Value
data A list of exercises (including non active ones, check the 'active' field).
{
    "error": false,
    "data": {
        "283": {
            "iid": "283",
            "c_id": "111",
            "id": "283",
            "title": "FINAL TEST",
            "description": "",
            "sound": "",
            "type": "2",
            "random": "0",
            "random_answers": "0",
            "active": "0",
            "results_disabled": "0",
            "access_condition": null,
            "max_attempt": "0",
            "start_time": null,
            "end_time": null,
            "feedback_type": "0",
            "expired_time": "0",
            "session_id": null,
            "propagate_neg": "0",
            "save_correct_answers": "0",
            "review_answers": "0",
            "random_by_category": "0",
            "text_when_finished": "",
            "display_category_name": "0",
            "pass_percentage": "70",
            "question_selection_type": "1",
            "hide_question_title": "0",
            "hide_attempts_table": "0",
            "extra_client": "ZARA",
            "created_by": "jdoe",
            "updated_by": "jdoe"
        }
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=course_exercises' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}'   \
--form 'course={courseId}' 

user_profile

Get information about your user profile (not the right service to get information from another user).

Call:

Key Value
action user_profile
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate

Response:

Key Value
data An array of user profile information. See corresponding code
{
  "error": false,
  "data": {
    "pictureUri": "http://YOURCHAMILO/main/img/unknown.jpg",
    "id": 1,
    "status": 1,
    "fullName": "lastname, firstname",
    "username": "admin",
    "officialCode": "ADMIN",
    "phone": "(000) 001 02 03",
    "extra": [
      {
        "title": "Skype",
        "value": ""
      },
      {
        "title": "LinkedInUrl",
        "value": ""
      }
    ]
  }
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=user_profile' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' 

Php Example:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getUserProfile($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'user_profile',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get user profile because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get the list of calendar events from inside the given course.
$userProfile = getUserProfile($apiKey);
echo json_encode($userProfile);

course_learnpaths

Get a list of learning paths inside a specific course.

Call:

Key Value
action course_learnpaths
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session

Response:

Key Value
data A list of learning paths categories from the course, containing lists of learning paths. See corresponding code

course_learnpath

Get redirected to a specific learning path (through a Location header).

Call:

Key Value
action course_learnpath
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session
lp_id (REQUEST) Internal ID of the learning path. If not defined, defaults to "1" (which doesn't really make sense for now)

Response: This service redirects the caller to the learning path (web).

save_course

Create a new empty course.

Call:

Key Value
action save_course
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id_campus (POST) The ID of the URL if multi-URL campus. It will be added in the wanted_code. For example, `$params['wanted_code'] = 'CAMPUS_'.$idCampus.'_'.$wantedCode;` Defaults to 1 (which is the right one if not using multi-URL)
title (POST) (string) The title of the course
wanted_code (POST) (string) The code expected for the course (unique, so if a conflict occurs, Chamilo will try to generate a variation of that code)
remove_campus_id_from_wanted_code (POST) (int) Removes the 'CAMPUS_'.$idCampus.'_' from the wanted code.
disk_quota (POST) The maximum size of the course documents, expressed in *bytes*!!! (not MB)
language (POST) (string) Course language, i.e. english, french, spanish
visibility (POST) A visibility status (from 0 to 4). See corresponding code
extra_ABC Where ABC is the name of an extra field variable.

Response:

Key Value
data An array of results and course info. See corresponding code

save_user

Create a new user.

Call:

Key Value
action save_user
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
firstname (POST)
lastname (POST)
auth_source (POST) Defaults to "platform"
status (POST) See corresponding code
email
loginname (POST) The desired username
password (POST)
original_user_id_name (POST) If this user exists in the calling system, Chamilo can keep it as a field named with a given key. This is the name of the key.
original_user_id_value (POST) This is the value of the user ID in the external system (see previous line)
extra (POST) Optional: An array of extra fields ('field_name' => ..., 'field_value' => ...)
language (POST) The English name of the language of the user (english, french, spanish, etc) as a string
phone (POST) Optional: The phone number
expiration_date (POST)

Response:

Key Value
data The user ID (in an array) if successful. 0 (in an array) otherwise

Code example in PHP:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @throws Exception
 *
 * @return string
 */
function authenticate() {
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : ' . $response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : ' . $jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @throws Exception
 *
 * @return int
 */
function createUser($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'save_user',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                // data for new user
                'firstname' => 'Test User',
                'lastname' => 'Chamilo',
                'status' => 5, // student
                'email' => '[email protected]',
                'loginname' => 'restuser',
                'password' => 'restuser',
                'original_user_id_name' => 'myplatform_user_id', // field to identify the user in the external system
                'original_user_id_value' => '1234', // ID for the user in the external system
                'extra' => [
                    [
                        'field_name' => 'age',
                        'field_value' => 29,
                    ],
                ],
                'language' => 'english',
                //'phone' => '',
                //'expiration_date' => '',
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : ' . $response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('User not created because : ' . $jsonResponse->message);
    }
    return $jsonResponse->data[0];
}

$apiKey = authenticate();

//Creating a new user restuser
$userId = createUser($apiKey);
echo 'ID of new user: '.$userId;

save_user_get_apikey

Create a user and assign its api_key.

It receives same data as in save_user but the response include the API key created for the user.

Response:

{
  "error": false,
  "data": {
    "id": 67,
    "api_key": "1df0fec7392170874b5dfaacb8d311d5"
  }
}

update_user_apikey

Update the API key for a user.

Make a POST request.

Key Value
action update_user_apikey
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
user_id The ID of the user whose api key will be changed
current_api_key The current api_key for the user $user_id

Example:

POST http://localhost/main/webservices/api/v2.php
Content-Type: application/x-www-form-urlencoded

action=update_user_apikey&username=bbaggins&api_key=48c1ca6928e505b704fd16a3583911a8&user_id=12&current_api_key=48c1ca6928e505b704fd16a3583911a8
{
  "error": false,
  "data": {
    "api_key": "7453f314754fadcbbabf36b7c33a207b"
  }
}

subscribe_user_to_course

Subscribe a given user to a given course.

Call:

Key Value
action subscribe_user_to_course
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course_id (POST) Internal (int) ID of the course to subscribe to
course_code (POST) Optional: Code (string) of the course (retrieved from the course ID if not provided)
user_id (POST) Internal (int) ID of the user to subscribe
status (POST) Optional int value. 5 = student, 1 = teacher, Default value is 5.

Response:

Key Value
data Array containing the boolean value true on success, false on failure

unsubscribe_user_from_course

Unsubscribe a given user to a given course.

Call:

Key Value
action subscribe_user_to_course
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course_id (POST) Internal (int) ID of the course to subscribe to
course_code (POST) Optional: Code (string) of the course (retrieved from the course ID if not provided)
user_id (POST) Internal (int) ID of the user to subscribe

add_campus

Add an additional URL to a multi-URL setup.

Call:

Key Value
action add_campus
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
url (POST) The desired URL for the new... URL
description (POST) A description to be shown in the administration panel for multi-URL management
active (POST) 0 to create the new URL as "dormant", 1 to create it and make it active straight away

Response:

Key Value
data Array containing a success status and an 'id_campus' field with the ID of the new URL. See corresponding code

edit_campus

Edit the information for one existing URL in a multi-URL setup.

Call:

Key Value
action edit_campus
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id (POST) The internal (int) ID of the URL
url (POST) The new URL
description (POST) A description to be shown in the administration panel for multi-URL management
active (POST) 0 to make the URL "dormant", 1 to make it active

Response:

Key Value
data Array containing the boolean value true on success, false on failure

delete_campus

Delete an existing URL in a multi-URL setup. Very dangerous service to use!

Call:

Key Value
action delete_campus
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id (POST) The internal ID of the URL

Response:

Key Value
data An array with 'status' and 'message' entries. Status = boolean true on success, false on failure.

delete_course

Delete a course. Very dangerous service to use!

Call:

Key Value
action delete_course
api_key The apiKey you received from the call to authenticate
course_id Course id
course_code Or course code (optional)

delete_user

Delete a user and all results related to this user. Very dangerous service to use!

Call:

Key Value
action delete_user
api_key The apiKey you received from the call to authenticate
user_id Internal user_id

save_session

Create a new session.

Call:

Key Value
action save_session
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
name (POST) The name of the session
coach_username (POST) Internal user_id (int) of the user to be considered a general coach for the session
access_start_date (POST) Date of start of access (used for all dates). Format: yyyy-mm-dd hh:ii:ss
access_end_date (POST) Date of end of access (used for all dates). Format: yyyy-mm-dd hh:ii:ss
description (POST) The session description (rarely used except in sessions catalogue)
id_campus (POST) Optional: internal (int) ID of the URL, if in a multi-URL setup and we do not create the session in the default URL
extra (POST) A table of session extra fields like extra[extra_EXTRAFIELDNAME] = value

Response:

Key Value
data Array of results. See corresponding code
{
  "error": false,
  "data": {
    "status": true,
    "message": "A new session has been created",
    "id_session": 2
  }
}

Curl example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=save_session' \
--form 'api_key={api_key}' \
--form 'username={username}' \
--form 'name=Session api test' \
--form 'coach_username=3' \
--form 'access_start_date=2020-09-10 00:00:00' \
--form 'access_end_date=2026-09-10 00:00:00' \
--form 'description=Session api description'

Code example in PHP:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
        'verify' => false,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function createSession($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
        'verify' => false,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'save_session',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                // data for new session
                'name' => 'Test Session',
                'coach_username' => 1, // user_id of CoachUsername that needs to already exist in Chamilo
                'access_start_date' => '2020-01-15 15:00:00',
                'access_end_date' => '2021-01-15 15:00:00',
                'description' => 'My complete text description of the session',
                'extra' => [
                    [
                        'extra_Price' => '200', // the "Price" session extra field needs to be already created in Chamilo
                    ],
                ],
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content,true);

    if ($jsonResponse['error']) {
        throw new Exception('Session not created because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data']['id_session'];
}

$apiKey = authenticate();


//Creating a new session Test Session
$sessionId = createSession($apiKey);
echo 'ID of new session: '.$sessionId;

update_session

update a session.

Call:

Key Value
action save_session
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
session_id (POST) (int) Internal session id to be updated
reset (POST) Optional: boolean 0 by default to only modify the field passed in parameter. If reset is set to 1 then all the session field will be reinitialised and only the parameter passed to the call will be set.
name (POST) (Opcional) The name of the session
id_coach (POST) (Opcional) Internal user_id (int) of the user to be considered a general coach for the session
session_category_id (POST) (Opcional) Internal session category id (int) of the category in which the session should be.
description (POST) (Opcional) HTML block of the session description (text)
show_description (POST) (Opcional) boolean to indicate if the session description should be presented
duration (POST) (Opcional) Number of days of the session (int) only used if the session is by duration and not by dates
visibility (POST) (Opcional) number of the time of visibility when ending the session (int) that could have the following values (1 : read only, 2 : Accessible, 3 : Not Accessible)
promotion_id (POST) (Opcional) Internal promotion_id (int) in which the session is included
display_start_date (POST) (Opcional) Date to show for the begining of the session. Format: yyyy-mm-dd hh:ii:ss
display_end_date (POST) (Opcional) Date to show for the end of the session. Format: yyyy-mm-dd hh:ii:ss
access_start_date (POST) (Opcional) Date of start of access. Format: yyyy-mm-dd hh:ii:ss
access_end_date (POST) (Opcional) Date of end of access. Format: yyyy-mm-dd hh:ii:ss
coach_access_start_date (POST) (Opcional) Date of start of access for coaches. Format: yyyy-mm-dd hh:ii:ss
coach_access_end_date (POST) (Opcional) Date of end of access for coaches. Format: yyyy-mm-dd hh:ii:ss
send_subscription_notification (POST) (Opcional) boolean to define if new users of the session will be notified of their subscription
extra (POST) A table of session extra fields like extra[extra_EXTRAFIELDNAME] = value

Response:

Key Value
data Array of results. See corresponding code
{
  "error": false,
  "data": {
    "status": true,
    "message": "Session updated",
    "id_session": "2"
  }
}

Curl example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=update_session' \
--form 'api_key={api_key}' \
--form 'username={username}' \
--form 'session_id=2' \
--form 'reset=0' \
--form 'name=updated session name' \
--form 'id_coach=3' \
--form 'access_start_date=2020-09-10 00:00:00' \
--form 'access_end_date=2026-09-10 00:00:00' \
--form 'description=Session api description updated'

Code example in PHP:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
        'verify' => false,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function updateSession($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
        'verify' => false,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'update_session',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                // data for session update
                'session_id' => '2',
                'reset' => '0',
                'name' => 'updated session name',
                'id_coach' => 3, // user_id of Coach that needs to already exist in Chamilo
                'access_start_date' => '2020-01-15 15:00:00',
                'access_end_date' => '2021-01-15 15:00:00',
                'description' => 'My complete updated text description of the session',
                'extra' => [
                    [
                        'extra_Price' => '200', // the "Price" session extra field needs to be already created in Chamilo
                    ],
                ],
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content,true);

    if ($jsonResponse['error']) {
        throw new Exception('Session not updated because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data']['id_session'];
}

$apiKey = authenticate();


//update a session with id = 2 
$sessionId = updateSession($apiKey);
echo 'ID of updated session: '.$sessionId;

get_users

Get a list of users' id, firstname, lastname and e-mail. Filtered by status (you must provide a status, or "role", if you prefer).

Call:

Key Value
action get_users
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
status (POST) Required: role of users you want.
id_campus (POST) Optional: Internal (int) ID of the URL if in multi-URL setup
extra_fields (POST) Optional: Comma-separated list of profile fields (available since 1.11.20)

Example

curl --location 'https://{CHAMILO_ URL}/main/webservices/api/v2.php?action=get_users&username={USERNAME}&api_key={API_KEY}&status=5&extra_fields=timezone,skype'

Response example:

    "error": false,
    "data": [
        {
            "id": "43135",
            "firstname": "Martin",
            "lastname": "McFly",
            "email": "[email protected]",
            "username": "martin",
            "timezone": "",
            "skype": ""
        }
    ]

Note: "username" is only available since 1.11.20.

get_courses

Get a list of all the courses of the given URL (if multi-URL setup).

Call:

Key Value
action get_courses
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id_campus (POST) Internal (int) ID of the URL (use "1" if you don't know)

Response example:

{
    "error": false,
    "data": [
        {
            "id": "13",
            "room_id": null,
            "title": "Business Intelligence 3",
            "code": "BI3",
            "directory": "BI3",
            "course_language": "english",
            "description": "Course Description",
            "category_code": "PC",
            "visibility": "2",
            "show_score": "1",
            "tutor_name": null,
            "visual_code": "BI3",
            "department_name": null,
            "department_url": "",
            "disk_quota": "100000000",
            "last_visit": "2022-12-27 22:48:54",
            "last_edit": "2022-12-27 14:21:27",
            "creation_date": "2022-12-27 14:21:27",
            "expiration_date": "2023-12-27 14:21:27",
            "subscribe": "1",
            "unsubscribe": "0",
            "registration_code": null,
            "legal": null,
            "activate_legal": null,
            "add_teachers_to_sessions_courses": null,
            "course_type_id": null,
            "real_id": "13"
        }
    ]
}

get_courses_from_extra_field

Get a list of all the courses of the given URL (if multi-URL setup) that matches an extra field value.

Call:

Key Value
action get_courses
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
extra_field_variable Your extra field variable
extra_field_value Your extra field value
id_campus (POST) Internal (int) ID of the URL (use "1" if you don't know)

get_sessions

Get a list of sessions. Optionally filtered by URL ID

Call:

Key Value
action get_sessions
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id_campus (POST) Optional: The internal (int) ID of the URL, if using multi-URL mode

Example request (Postman):

get_sessions

Response:

Key Value
data An array of results
{
  "error": false,
  "data": [
    {
      "id": "1",
      "name": "First session",
      "access_start_date": "2022-09-01 14:00:00",
      "access_end_date": "2023-01-31 22:45:00",
    },
    {
      ...
    }
  ]
}

Curl example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=get_sessions' \
--form 'username=jperry' \
--form 'api_key={api_key}' \
--form 'id_campus=1' \

add_courses_session

Add some courses to the given session. Warning: courses not given in the list and already present in the session will be removed from the session (with possibly dramatic consequences).

Call:

Key Value
action add_courses_session
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id_session (POST) The internal (int) ID of the session to add the courses to
list_courses (POST) An array of internal course IDs that we want to add to the session.
import_assignments (POST) Import the course base assignments into the session or not. (int value 1 or 0)

Response:

Key Value
data An array of results. See corresponding code
{
  "error": false,
  "data": {
    "status": true,
    "message": "Update successful"
  }
}

Curl example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=add_courses_session' \
--form 'username=jperry' \
--form 'api_key={api_key}' \
--form 'id_session=1' \
--form 'list_courses[]=1' \
--form 'list_courses[]=2' \
--form 'list_courses[]=3' \
--form 'import_assignments=1'

Code example in PHP:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of addCoursesToSession() below to suit your needs.
 */

use GuzzleHttp\Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @throws Exception
 *
 * @return string
 */
function authenticate() {
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : ' . $response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : ' . $jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @throws Exception
 *
 * @return int
 */
function addCoursesToSession($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'add_courses_session',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                // data for courses and session
                'id_session' => 1,
                'import_assignments' => 1,
                'list_courses' => [
                    [
                        '1',
                        '2',
                        '3',
                    ],
                ],
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : ' . $response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Courses not added because : ' . $jsonResponse->message);
    }
    return $jsonResponse->data[0];
}

$apiKey = authenticate();

//adding courses with id 1, 2, 3 to session with id 1
if (addCoursesToSession($apiKey){
    {echo 'Courses successfully added';}
}

subscribe_users_to_session

Subscribe a list of users to the given session.

subscribe_users_to_session name only available since 1.11.20, was previously add_users_session (still supported)

Call:

Key Value
action add_users_session
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id_session (POST) Internal (int) ID of the session to add users to
list_users (POST) An array of users (int) IDs

Example request (Postman):

subscribe_users_to_session

Response:

Key Value
data Array with status (currently only returns true)
{
  "error": false,
  "data": {
    "status": true,
    "message": "Users added"
  }
}

Curl request example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=add_users_session' \
--form 'username=jperry' \
--form 'api_key={api_key}' \
--form 'id_session=1' \
--form 'list_users[]=2' \
--form 'list_users[]=3' \
--form 'list_users[]=4'

PHP code request example:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,

    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function addUsersToSession($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,

    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'add_users_session',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                // data for users and session
                'id_session' => 1,
                'list_users' => [
                    '5',
                    '6',
                    '7',
                ],
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Users not assigned to session because : '.$jsonResponse->message);
    }
    return $jsonResponse->data[0];
}

$apiKey = authenticate();

//adding users with id 5, 6, 7 to session with id 1
if (addUsersToSession($apiKey)) {
    echo 'Users successfully added';
}

get_users_subscribed_to_session

Get the list of users subscribed to the given session.

Call:

Key Value
action get_users_subscribed_to_session
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id_session (POST) The internal (int) ID of the session
move_info (POST) Optional: 0 or 1, whether we want information about users having moved between sessions at some point (a special, little used, extra feature of Chamilo)

Example request (Postman):

get_users_subscribed_to_session

Response:

Key Value
data An array of user cards where:
- status is mostly 0
- moved_to is a session ID where the user has moved
-moved_status is a number representing the state of the move
- moved_at is a datetime of the move
{
  "error": false,
  "data": [
    {
      "user_id": "1",
      "username": "mmcfly",
      "firstname": "Marty",
      "lastname": "McFly",
      "status": "0",
      "moved_to": null,
      "moved_status": null,
      "moved_at": null
    },
    {
      ...
    }
  ]
}

Curl example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=get_users_subscribed_to_session' \
--form 'username=jperry' \
--form 'api_key={api_key}' \
--form 'id_session=1' \
--form 'move_info=1' \

unsubscribe_users_from_session

Unsubscribe users from the given session.

Call:

Key Value
action get_users_subscribed_to_session
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
id_session (POST) The internal (int) ID of the session
list_users (POST) Array of user IDs to be removed from the session

Example request (Postman):

unsubscribe_users_from_session

Response:

Key Value
data An array containing a status and a message
{
  "error": false,
  "data": {
      "status": true,
      "message": "User is now unsubscribed"
    }
}

Curl request example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=unsubscribe_users_from_session' \
--form 'username=jperry' \
--form 'api_key={api_key}' \
--form 'id_session=1' \
--form 'list_users[]=2' \
--form 'list_users[]=3' \
--form 'list_users[]=4'

save_forum_post

Add a forum post to a given forum (sessions not supported at this time).

Call:

Key Value
action save_forum_post
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
title (POST) The title for the new forum post
text (POST) The post text itself
thread (POST) (int)
forum (POST) (int)
parent (POST) (int)
notify (POST) (int)

Response:

Key Value
data An array containing the index 'registered' with the ID (iid) of the added post

user_sessions

Get the list of sessions of the current user

Call:

Key Value
action user_sessions
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate

Response:

Key Value
data An array of session categories, sessions and courses inside those sessions. See corresponding code
{
  "error": false,
  "data": [
    {
      "id": null,
      "name": null,
      "sessions": [
        {
          "name": "Sesion 1",
          "id": 1,
          "date": "De 30 de Septiembre del 2020 a las 12h10",
          "duration": null,
          "courses": [
            {
              "id": "1",
              "title": "English for beginners",
              "code": "ENGLISH101",
              "directory": "ENGLISH101",
              "pictureUrl": "http://YOURCHAMILO/main/img/session_default.png",
              "urlPicture": "http://YOURCHAMILO/main/img/session_default.png",
              "teachers": ""
            },
            {
              "id": "2",
              "title": "Español para iniciantes",
              "code": "SPANISH101",
              "directory": "SPANISH10116b4",
              "pictureUrl": "http://YOURCHAMILO/main/img/session_default.png",
              "urlPicture": "http://YOURCHAMILO/main/img/session_default.png",
              "teachers": ""
            },
            {
              "id": "3",
              "title": "Français pour débutants",
              "code": "FRENCH101",
              "directory": "FRENCH1018584",
              "pictureUrl": "http://YOURCHAMILO/main/img/session_default.png",
              "urlPicture": "http://YOURCHAMILO/main/img/session_default.png",
              "teachers": ""
            }
          ]
        }
      ]
    }
  ]
}

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=user_sessions' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' 

Php Example:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getUserSessions($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,
    ]);

    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'user_sessions',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get user profile because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'];
}

$apiKey = authenticate();


//Get the list of sessions of the current user
$userSessions = getUserSessions($apiKey);
echo json_encode($userSessions);

save_user_message

Send an internal message from the current user.

Call:

Key Value
action save_user_message
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
receivers (POST) Array of internal user IDs for the users we want to send the message to
subject (POST) (string)
text (POST) (string)

Response:

Key Value
data An array with the 'sent' index (currently always true)

message_users

Get users to whom the current user is allowed to send internal messages.

Call:

Key Value
action message_users
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
q (REQUEST) A query string to filter users on

Response:

Key Value
data An array of [id => ..., name => ...] with details about users we can contact

save_course_notebook

Add a notebook entry in the given course/session

Call:

Key Value
action save_course_notebook
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session
title (POST) The title of the personal notebook entry
text (POST) Contents of the personal notebook entry

Response:

Key Value
data An array containing the index 'registered' with the ID (iid) of the added notebook

save_forum_thread

Add a forum thread in the given forum.

Call:

Key Value
action save_forum_thread
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course Internal ID of the course in Chamilo
session Optional: the internal ID of the session
title (POST) The title of the thread
text (POST) The text of the thread
forum (POST) Internal (int) ID of the forum
notify (POST) 0/1: Whether to notify the user (by e-mail) of any subsequent change to the thread

Response:

Key Value
data An array containing the index 'registered' with the ID (iid) of the added thread

create_session_from_model

Creating a new session based on a model and updating indicated fields

Call: Http method: POST

Key Value
action create_session_from_model
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
modelSessionId Internal (int) ID of the session to use as a model
sessionName Name of the new session
startDate Starting date of the new session
endDate Ending date of the new session
extraFields (optional) An array of extra fields to be set for the new session like extrafields[extraFieldName]=extraFieldValue
duplicateAgendaContent (optional) A boolean, it allows duplicate the agenda events from the model session course in the new session with its relative dates
curl --location --request POST 'http://localhost/main/webservices/api/v2.php' \
--form 'action=create_session_from_model' \
--form 'username=admin' \
--form 'api_key=dc5be67b57217631d9a0da9af6f4fab5' \
--form 'model_session_id=3' \
--form 'sessionName=A new session' \
--form 'startDate=2021-12-22 22:00:00' \
--form 'endDate=2022-01-22 22:00:00'

Response:

{
  "error": false,
  "data": [
    1
  ]
}

data: Array with new session id

subscribe_user_to_session_from_username

Subscribe user based on username (loginName) to the given session.

Call:

Key Value
action subscribe_user_to_session_from_username
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
sessionId (POST) Internal (int) ID of the session to subscribe the user to
loginName (POST) username of the user to be added to the session

Response:

Key Value
data Array with boolean indicating the success or not

get_session_from_extra_field

Get the internal session ID of the corresponding session.

Call:

Key Value
action get_session_from_extra_field
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
fieldName (POST) Name of the extra field to search the session on
fieldValue (POST) value that will be searched for

Response:

Key Value
data Array with searched session id

update_user_from_username

Update a user based on username (loginName).

Call:

Key Value
action update_user_from_username
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
loginName (POST) username of the user to be updated
firstname (POST) Optional
lastname (POST) Optional
status (POST) Optional See corresponding code
email (POST) Optional
address (POST) Optional
roles (POST) Optional
profile_completed (POST) Optional: To enable or disable
auth_source (POST) Optional: Platform is the platform type set by default
official_code (POST) Optional: Code with which the user is displayed
picture_uri (POST) Optional: uri address of the profile picture
creator_id (POST) Optional
competences (POST) Optional
diplomas (POST) Optional
openarea (POST) Optional
teach (POST) Optional
productions (POST) Optional
active (POST) Optional: To enable or disable the user's ability to log in (0 or 1)
openid (POST) Optional
theme (POST) Optional
hr_dept_id (POST) Optional
language (POST) Optional: The English name of the language of the user (english, french, spanish, etc) as a string
phone (POST) Optional: The phone number
expiration_date (POST) Optional: Set the expiration date of the account. Format yyyy-mm-dd hh:ii:ss
extra (POST) Optional: An array of extra fields ('field_name' => ..., 'field_value' => ...)
enabled (POST) Deprecated: do not use

Successful response:

{
  "error": false,
  "data": [
    true
  ]
}

Bad answer with an illegal field:

{
  "error": true,
  "message": "Unsupported update. 'username_canonical'"
}

Curl example:
curl --location --request POST '{your_chamilo_url}/main/webservices/api/v2.php' \
--form 'action=update_user_from_username'
--form 'username=jperry' \
--form 'api_key={api_key}' \
--form 'loginName=mlanoix' \
--form 'firstname=new firstname' \
--form 'lastname=new lastname' \
--form 'status=1' \
--form '[email protected]' \
--form 'active=1' \
--form 'address=new address' \
--form 'profile_completed=1' \
--form 'official_code=new_official_code' \
--form 'expiration_date=2026-10-06 00:00:00' \
--form 'teach=teach as' Code example in PHP:

<?php
/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL='https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername='USERNAME';
$webservicePassword='PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,

    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function updateUserFromUsername($apiKey)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,

    ]);

    $response = $client->post('v2.php', [
        'form_params' => [
            // data for the user who makes the request
            'action' => 'update_user_from_username',
            'username' => $webserviceUsername,
            'api_key' => $apiKey,
            // data for the user to be updated
            'loginName' => 'TestUser',
            'firstname' => 'Test User',
            'lastname' => 'Chamilo',
            'status' => 5, // student
            'email' => '[email protected]',
            'active' => 1,
            'extra' => [
                [
                    'field_name' => 'age', // The "age" user extra field needs to already be created on Chamilo
                    'field_value' => 35,
                ],
            ],
            'language' => 'english',
            'expiration_date' => '2025-12-31 23:59:59',
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('User not updated because : '.$jsonResponse->message);
    }
    return $jsonResponse->data[0];
}


$apiKey = authenticate();

//update user TestUser
if (updateUserFromUsername($apiKey)){
    echo 'User updated successfully';
}

username_exist

Return if a username already exist

Call:

Key Value
action username_exist
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
loginname (POST) Username we want to know if it exist

Response:

Key Value
data Boolean true if loginname exist

Curl Example:

curl --location --request POST 'http://YOURCHAMILO/main/webservices/api/v2.php' \
--form 'action=username_exist' \
--form 'username={USERNAME}' \
--form 'api_key={api_key}' \
--form 'loginname={loginname}' 

Php Example:

<?php

/**
 * Test example to user API v2.php
 *
 * Using Guzzle' HTTP client to call the API endpoint and make requests.
 * Change URL on the first lines of createUser() below to suit your needs.
 */

use GuzzleHttp\Client as Client;

// set your URL, username and password here to use it for all webservices in this test file.
$webserviceURL = 'https://YOURCHAMILO/main/webservices/api/';
$webserviceUsername = 'USERNAME';
$webservicePassword = 'PASSWORD';

/**
 * Make a request to get the API key for admin user.
 *
 * @return string
 * @throws Exception
 *
 */
function authenticate()
{
    global $webserviceURL;
    global $webserviceUsername;
    global $webservicePassword;
    $client = new Client([
        'base_uri' => $webserviceURL,

    ]);


    $response = $client->post('v2.php', [
        'form_params' => [
            'action' => 'authenticate',
            'username' => $webserviceUsername,
            'password' => $webservicePassword,
        ],
    ]);

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $jsonResponse = json_decode($response->getBody()->getContents());

    if ($jsonResponse->error) {
        throw new Exception('Authentication failed because : '.$jsonResponse->message);
    }

    return $jsonResponse->data->apiKey;
}

/**
 * @param $apiKey
 *
 * @return int
 * @throws Exception
 *
 */
function getUserNameExist($apiKey, $loginname)
{
    global $webserviceURL;
    global $webserviceUsername;
    $client = new Client([
        'base_uri' => $webserviceURL,

    ]);


    $response = $client->post(
        'v2.php',
        [
            'form_params' => [
                // data for the user who makes the request
                'action' => 'username_exist',
                'username' => $webserviceUsername,
                'api_key' => $apiKey,
                'loginname' => $loginname,
            ],
        ]
    );

    if ($response->getStatusCode() !== 200) {
        throw new Exception('Entry denied with code : '.$response->getStatusCode());
    }

    $content = $response->getBody()->getContents();
    $jsonResponse = json_decode($content, true);

    if ($jsonResponse['error']) {
        throw new Exception('cant get user profile because : '.$jsonResponse['message']);
    }
    return $jsonResponse['data'][0];
}

$apiKey = authenticate();


//Return if a username already exist
$userNameExist = getUserNameExist($apiKey, 'admin');
if ($userNameExist == true) {
    echo "User name exist";
} else {
    echo "User doesnt name exist";

}

get_course_quiz_mdl_compat

This service roughly matches what the call to MDL's API core_course_get_contents function returns.

Call:

Method: POST

Key Value
action get_course_quiz_mdl_compat
username Your username, i.e. jperry
api_key The apiKey you received from the call to authenticate
course The course ID
session Optional. The session ID

Response:

Array of modules like MDL. Example:

[
  {
    "id": 2,
    "name": "Tests",
    "visible": 1,
    "summary": "",
    "summaryformat": 1,
    "section": 1,
    "hiddenbynumsections": 0,
    "uservisible": true,
    "modules": [
      {
        "id": 2,
        "url": "http://localhost/mdl/mod/quiz/view.php?id=2",
        "name": "Quiz One",
        "instance": 1,
        "visible": 1,
        "uservisible": true,
        "visibleoncoursepage": 1,
        "modicon": "http://localhost/mde/theme/image.php/boost/quiz/1589385181/icon",
        "modname": "quiz",
        "modplural": "Tests",
        "availability": null,
        "indent": 0,
        "onclick": "",
        "afterlink": null,
        "customdata": "",
        "noviewlink": false,
        "completion": 1,
        "completiondata": {
          "state": 0,
          "timecompleted": 0,
          "overrideby": null,
          "valueused": false
        }
      }
    ]
  }
]

get_users_subscribed_to_course

Get subscribed users

Call:

Method: POST

Key Value
action get_users_subscribed_to_course
course (int) Course id
api_key The apiKey you received from the call to authenticate

Response:

List of users:

Where status_rel: 1 = teacher 5 = student

{
  "error": false,
  "data": [
    {
      "user_id": "16",
      "username": "acalabaza",
      "firstname": "Aldo",
      "lastname": "Calabaza",
      "status_rel": "5"
    }
  ]
}

get_test_updates_list

Get all tests with last user attempt and his datetime

Call:

Method: POST

Key Value
action get_test_updates_list
api_key The apiKey you received from the call to authenticate
fields Optional array of extra field names. If provided, the service will return the values for the given fields in an item called "extra_" and the name of the field. Note that this will first search for that extra field in the exercise, but if not found, it will also look for that extra field in the course (in which the exercise is found).

Response:

Note that extra fields are returned with an extra_ prefix, and that created_by and updated_by provide the username of the user who created or modified the test.

List of tests:

{
  "error": false,
  "data": [
    {
      "id": "4",
      "title": "aiken",
      "last_attempt_time": "2022-10-07 08:12:15",
      "last_attempt_username": "admin",
      "c_id": "11",
      "extra_client": "ZARA",
      "created_by": "jdoe",
      "updated_by": "jdoe"
    }
  ]
}

get_test_average_results_list

Get tests result data.

Not suport for sessions.

By default, we give a pass grade if the score is greater than 50%.

Call:

Method: POST

Key Value
action get_test_average_results_list
ids (array) A comma-separated list of numerical c_quiz.iid
fields (array) Optional. A comma-separated list of extra fields that should be returned for each quiz. Extra fields will be returned as a list of fields prefixed by "extra_".
api_key The apiKey you received from the call to authenticate

Response:

List of test results data:

{
  "error": false,
  "data": [
    {
      "id": 4,
      "title": "aiken",
      "created_by": "jdoe",
      "updated_by": "jdoe",
      "type": "ExerciseAtTheEndOfTheTest",
      "completion": 0,
      "completion_method": "Success on users count",
      "number_of_last_attempts": 1,
      "average_score_in_percent": 0,
      "extra_client": "",
      "extra_country": ""
    }
  ]
}
Clone this wiki locally