Note:

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

Creating a web service and a web service function: Difference between revisions

From MoodleDocs
m (removing categories)
 
(135 intermediate revisions by 6 users not shown)
Line 1: Line 1:
{{Moodle_2.0}}
#REDIRECT [[Adding_a_web_service_to_a_plugin]]
WORK IN PROGRESS
 
In this document you will learn how to create a web service function.
 
This document expect that you first read the administration manual [[Setting_up_a_web_service]].<br/>
To explain how to write a new web service function, we will write a web service function ''create_groups($groups)''. This function create a group into a Moodle course.
 
This function will take a list of group object as parameters and it will return the same groups with their newly created id. If ever one group creation  fails, the function will throw an exception, and no creation will happen.
 
We'll finally add the web service function to a core web service.
 
== Preparation ==
We need to identify:
* '''the core functions''': for our case we will use ''groups_create_group()'' from [http://cvs.moodle.org/moodle/group/ /group/lib.php]. Of course not every core function exists and in some other cases you could have to write them. 
* '''the parameter types''': for our case we'll send a list of object. This object are groups, with id/name/courseid.
* '''the returned value types''': for our case we want to send back a list of group object with their id.
* '''the user capabilities''': for our case the user will need the ''moodle/course:managegroups'' capability.
 
== declare the web service function ==
Web service functions are declared into ''db/services.php'' of each component. In our case ''create_groups()'' is a core external function, so we will add the function to [http://cvs.moodle.org/moodle/lib/db/ /lib/db/services.php].
 
<code php>
$functions = array(
    'moodle_group_create_groups' => array(        //web service function name
        'classname'  => 'moodle_group_external',  //class containing the external function
        'methodname'  => 'create_groups',          //external function name
        'classpath'  => 'group/externallib.php',  //file containing the class/external function
        'description' => 'Creates new groups.',    //human readable description of the web service function
        'type'        => 'write',                  //database rights of the web service function (read, write)
    ),
);
</code>
 
Here you should ask yourself what is the difference between a web service function and an external function. Web service function could be considered as a redirection to the external function. The web service function name is the name that is served by web service server to the client. By this way the client doesn't know about the external functions.
 
The web service function name is arbitrary, but it must be globally unique so we highly recommend using the component name as prefix (and "moodle" for core functions).
 
== define the web service function description ==
Some web service protocol need a full description of the web service function parameters and return value. For example we need to generate a full WSDL for SOAP if we expect a JAVA/.Net client to call our function.<br/>
Moreover we implemented a web service parameters validation process that require a full description of these parameters.<br/>
In conclusion, you must write these descriptions. These descriptions are not applied on the web service function but the external function, remember that the web service function is just a kind of redirection.<br/><br/>
 
Descriptions are usually located into a class into an externallib.php in the component folder. You probably remember that we referenced this ''moodle_group_external'' class into [http://cvs.moodle.org/moodle/lib/db/ /lib/db/services.php]. Let's take a minuteto talk about the [http://cvs.moodle.org/moodle/group/ /group/externallib.php] that we need to create.
 
This file will contain all external functions. These functions are all related together. In our case the externallib.php file will contain all ''group'' related functions. For each external function, we will have:
* the external function, calling a core function.
* a function describing the parameters of the external function
* a function describing the return values of the external function
 
Now we'll have look to the description of the ''create_group($groups)'' parameters. All parameter descriptions are included into a function called ''externalfunctionname_parameters()''. In our case it will be ''create_groups_parameters()'' :
 
<code php>
    /**
    * Returns description of method parameters
    * @return external_function_parameters
    */
    public static function create_groups_parameters() {
        return new external_function_parameters(
            array(
                'groups' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'courseid' => new external_value(PARAM_INT, 'id of course'),
                            'name' => new external_value(PARAM_TEXT, 'multilang compatible name, course unique'),
                            'description' => new external_value(PARAM_RAW, 'group description text'),
                            'enrolmentkey' => new external_value(PARAM_RAW, 'group enrol secret phrase'),
                        )
                    )
                )
            )
        );
    }
</code>
 
Ok you are probably already here :) We have to understand this function very well. There is different approaches to understand this function, here is my personal one.<br/>
The function ''xxx_parameters()'' always return an ''external_function_parameters'' object. This object is initialized with an associative array. This array contains the parameter descriptions. If the external function have three parameters, this array will have three elements, the keys being the paramters name.
Each of its element is a parameter description. A parameter can be a list (external_multiple_structure), an object (external_single_structure) or a primary type (external_value).
 
Our create_groups() function expect one parameter named ''groups'', so we will first write:
 
<code php>
    /**
    * Returns description of method parameters
    * @return external_function_parameters
    */
    public static function create_groups_parameters() {
        return new external_function_parameters(
            array(
                'groups' => ...
               
            )
        );
    }
</code>
 
This ''groups'' parameter is a list of group. So we will write :
 
<code php> 
                'groups' => new external_multiple_structure(
                    ...
                )         
</code>
 
An external_multiple_structure object (list) can be initialized with external_single_structure (object), external_value (primary type) or another external_multiple_structure (list). You will respectively obtain a list of a unique object type, a list of a unique primary type, or a list of a list. These last case being probably bad design.<br/>
In our case we want a list of group, a group being a object. Have a look on how would describe a group :
 
<code php>           
                    new external_single_structure(
                        array(
                            'courseid' => ...,
                            'name' => ...,
                            'description' => ...,
                            'enrolmentkey' => ...,
                        )
                    )         
</code>
 
From this code you can guess that a external_single_structure is initialize with an associative array. This array containing the object attibuts.<br/>
Thus a list of group will be defined :
 
<code php> 
                'groups' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'courseid' => ...,
                            'name' => ...,
                            'description' => ...,
                            'enrolmentkey' => ...,
                        )
                    )
                )         
</code>
 
Every of the group attribut are primary type. ''courseid'' is an integer. ''name'' is a string, ''description'' is a string, and ''enrolmentkey'' is also a string. To define a primary type we use the ''external_value'' object. This ''external_value'' is initialize with a non associative array containing three elements:
# the primary type
# a human readable description
# is the parameter optional (if the parameter is mandatory we don't need this third element)
 
For example for the ''courseid'' and ''name'' attribut we would define:
 
<code php>               
                            'courseid' => new external_value(PARAM_INT, 'id of course'),
                            'name' => new external_value(PARAM_TEXT, 'multilang compatible name, course unique'),                       
</code>
 
So our list of object description will be :
 
<code php> 
                'groups' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'courseid' => new external_value(PARAM_INT, 'id of course'),
                            'name' => new external_value(PARAM_TEXT, 'multilang compatible name, course unique'),
                            'description' => new external_value(PARAM_RAW, 'group description text'),
                            'enrolmentkey' => new external_value(PARAM_RAW, 'group enrol secret phrase'),
                        )
                    )
                )         
</code>
 
Now you should be able to understand this parameter description function. You also should be able to deduce how to write the return value description function.
 
Return value function always return one primary or complex value, so we don't need to return external_function_parameters object. In our case we want to return the exact same list of groups. The only change being that we want the group to have an id attribut.
 
<code php>
public static function create_groups_returns() {
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'id' => new external_value(PARAM_INT, 'group record id'),
                    'courseid' => new external_value(PARAM_INT, 'id of course'),
                    'name' => new external_value(PARAM_TEXT, 'multilang compatible name, course unique'),
                    'description' => new external_value(PARAM_RAW, 'group description text'),
                    'enrolmentkey' => new external_value(PARAM_RAW, 'group enrol secret phrase'),
                )
            )
        );
    }
</code>
 
== define the external function ==
 
== Add the web service function into a service ==
In some specific case we could want to set a service by default, so the Moodle administrator doesn't need to set a new one. We can do that by writing the following code:
 
<code php>
  $services = array(
      'groupservice' => array(                                                //the name of the web service
          'functions' => array ('moodle_add_groups', 'moodle_create_groups'), //web service functions of this service
          'requiredcapability' => 'some/capability:specified',                //if set, the web service user need this capability to access
                                                                              //any function of this service                 
          'restrictedusers' = >1,                                            //if enabled, the Moodle administrator must link some user to this service
                                                                              //into the administration
          'enabled'=>0,                                                      //if enabled, the service can be reachable on a default installation
      )
  );
</code>
 
In this code we created a service called ''groupservice''. This service contains two functions ''moodle_add_groups''/''moodle_create_groups''. <br/>
This possibility to preset a service exists to facilitate the administrator life. He can easily enable a bunch of function. <br/>
However it is not possible for an administrator to add/remove any function from preset service. For security purpose, it is not a recommended to preset a service.
 
== test the web service function ==
Moodle is bundled with a test client that can be accessed into [http://cvs.moodle.org/moodle/webservice/ webservice/testclient.php]<br/>
In order to support our function we will need to add a form into [http://cvs.moodle.org/moodle/webservice/ webservice/testclient_forms.php].
 
== create your own client ==
 
==See also==
* [[Web services]]
* [[External services security]]
* [[External services description]]
* [[Setting_up_a_web_service]]
 
[[Category:Web Services]]

Latest revision as of 09:08, 27 February 2012