Consume Moodle Web Service

Asked

Viewed 2,985 times

4

I am trying to consume the webservice of Moodle, following a js/Rest example I found on github, I created a test.php with the code below (changing the domainname and token) but when I call the page I get nothing in the variable Answer, by Chrome I get a Failed to load Resource: net::ERR_TIMED_OUT inside the server.php.

My idea is to consume another function of the webservice, but not even the simple example I’m getting, Moodle is already with the functions of webservice/Rest enabled and everything else.

Something I’d like to add is that I can use the service by the url (below is an example of another function of the webservice):

/moodle/webservice/rest/server.php?wstoken=meutoken&wsfunction=core_user_get_users&moodlewsrestformat=json&criteria[0][key]=departament&criteria[0][value]=1

So he returns me a json, but I needed to use $.ajax to manipulate this data, in case show the name of some user using an email or other parameter.

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    var domainname = 'http://yourmoodle';
    var token = 'acabec9d208978d986986g987657ffg9';
    var functionname = 'core_user_create_users';
    var serverurl = domainname + '/webservice/rest/server.php' ;
    //add params into data
    var userstocreate = [{  username: 'testusername1',
                            password: 'testpassword1',
                            firstname: 'testfirstname1',
                            lastname: 'testlastname1',
                            email: '[email protected]',
                            auth: 'manual',
                            idnumber: 'testidnumber1',
                            lang: 'en',
                            theme: 'standard',
                            timezone: '-12.5',
                            mailformat: 0,
                            description: 'Hello World!',
                            city: 'testcity1',
                            country: 'au',
                            preferences: [
                                {type: 'preference1', value: 'preferencevalue1'},
                                {type: 'preference2', value: 'preferencevalue2'}
                            ]
                         },
                         {  username: 'testusername2',
                            password : 'testpassword2',
                            firstname : 'testfirstname2',
                            lastname : 'testlastname2',
                            email : '[email protected]',
                            timezone : 'Pacific/Port_Moresby'
                         }
                     ];
    var data = {
                wstoken: token,
                wsfunction: functionname,
                moodlewsrestformat: 'json',
                users: userstocreate
                }
    var response = $.ajax(
                            {   type: 'POST',
                                data: data,
                                url: serverurl
                            }
                         );
    console.info(response);
});
</script>
</head>
<body>
    Check your Javascript console for the "responseText" value.
</body>
</html>

php server. (Pattern of the Moodle)

<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.


/**
 * REST web service entry point. The authentication is done via tokens.
 *
 * @package    webservice_rest
 * @copyright  2009 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

/**
 * NO_DEBUG_DISPLAY - disable moodle specific debug messages and any errors in output
 */
define('NO_DEBUG_DISPLAY', true);

/**
 * NO_MOODLE_COOKIES - no cookies with web service
 */
define('NO_MOODLE_COOKIES', true);

require('../../config.php');
require_once("$CFG->dirroot/webservice/rest/locallib.php");

if (!webservice_protocol_is_enabled('rest')) {
    debugging('The server died because the web services or the REST protocol are not enable',
        DEBUG_DEVELOPER);
    die;
}

$server = new webservice_rest_server(WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN);
$server->run();
die;
  • Post the code that is on server.php. If it’s too big, just put it back

  • I don’t know if it helps much, but if I call the functions directly in the url, passing the parameters I can use the webservice, but in the ajax request no.

  • Will you even put TOKEN and Avascript? Anyone can see and will have access to your Token.

  • Yes, in the real case I would use a token to enable another function, for example something to visualize someone’s name, no problem the person know the token, this code of "create users" I put by the same structure.

2 answers

2


I couldn’t understand why the js code doesn’t work but I was able to consume using a php example that is in the same repository as the javascript example.

<?php



$token = 'meutoken';
$domainname = 'http://meumoodle';
$functionname = 'core_user_get_users';


$restformat = 'json'; //Also possible in Moodle 2.2 and later: 'json'
                     //Setting it to 'json' will fail all calls on earlier Moodle version
//////// moodle_user_create_users ////////
/// PARAMETERS - NEED TO BE CHANGED IF YOU CALL A DIFFERENT FUNCTION
$user1 = new stdClass();
$user1->key = 'username';
$user1->value = 'myvalue';

$users = array($user1);
$params = array('criteria' => $users);



$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
require_once('./curl.php');
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->get($serverurl . $restformat, $params);
$json = json_encode($resp);

$obj = json_decode($resp);


?>

Then just print out the $obj amount. In this example I put as answer I am using another function "core_user_get_users", but the basis is the same, it is only necessary to change the parameters according to the documentation of the Moodle API.

  • Running in version 3

0

I was having the same problem as you, but I was able to solve by watching your code.

The Moodle has some conditions to enter data in the flock that change according to the version of the platform.

For example, in the version I am using the password must have at least one uppercase character and an alphanumeric character.

This was the error message that returned when I used part of your code. So just change the password to the requested conditions to work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.