Creating custom services

June 18, 2021

Web services is a way we can provide information to a device via an internet connection, such as a list of contents, entities, users, among others.

In Drupal, we use the Services Module which allows us to perform these services, as explained in this blog [Creando contenido con Rest Services]

This time we will create a custom module, which you define a service to return a list of users.

rootstack_services_custom.info

 
name = Rootstack Custom services
description = My custom Rootstack Drupal module service.
package = Rootstack
core = 7.x
dependencies[] = services
dependencies[] = rest_server

rootstack_services_custom.module

 
/**
 * Implements hook_permission().
 */
function rootstack_services_custom_permission() {
  return array(
    'rootstack get users' => array(
      'title' => t('Retrieve a list of users.'),
    ),
  );
}

rootstack_services_custom.services.inc

 
/**
 * Implementation of hook_services_resources().
 */
function rootstack_services_custom_services_resources() {
  return array(
    'rootstack_services_users' => array(
      'retrieve' => array(
        'file' => array(
          'type' => 'inc',
          'module' => 'rootstack_services_custom',
          'name' => 'rootstack_services_custom.resources',
        ),
        'help' => t('Gets a count of users.'),
        'callback' => 'rootstack_services_custom_get_user',
        'args' => array(
          array(
            'name' => 'uid',
            'type' => 'string',
            'optional' => TRUE,
            'source' => array('param' => 'uid'),
            'description' => t('User ID.'),
          ),
        ),
        'access arguments' => array('rootstack get users'),
      ),
    ),
  );
}

rootstack_services_custom.resources.inc

 
/**
 * Callback function for retrieve list of users.
 */
function rootstack_services_custom_get_user($uid) {
  $query = db_select('users', 'f');
  $query->fields('f', array('name', 'mail'));
  if ($uid) {
    $query->condition('f.uid', $uid, '=');
  }
  return $query->execute()->fetchAll();
}

Configurations from interface:

  • Activate the module (admin / modules)
  • Assign permissions (admin / people / permissions)
  • Generate service, which can be done from the interface (admin / structure / services)
  • From the Resources tab, select the resource created.

Conclusion

Service creation is very useful and simple to perform, not only allows us to consult the database, but also to the Solr indexing, like control allows us to have permissions created for each service.

Share

Table of contents

Quick Access

Yes, I liked thiscontent.