Friday 15 March 2019

Create the REST Resource web service Drupal 8

Create RESTful web service

RESTful web service is now in Core in Drupal 8. Expose entities as RESTful resources can be used to
  • Build a decoupled Drupal site.
  • Native mobile IOS/Android app consume/feed a Drupal Site.
  • To integrate with web service.
Drupal 8 web services uses XML and JSON. XML & JSON are method to provide customizable data in the form of API.

To create RESTful web service, first of all we need following modules.
Drupal 8 Core
HAL: Serializes entities using Hypertext Application Language.
HTTP Basic Authentication: Provides the HTTP Basic authentication provider
RESTful Web Services: Exposes entities and other resources as RESTful web API
Serialization: Provides a service for (de)serializing data to/from formats such as JSON and XML

Drupal 8 Contrib
REST UI: Provides a user interface to manage REST resource

To enable RESTful Web Services module, Serialization module must be enabled. Enable these modules with the help of drush command (drush en serialization, rest -y) or from interface by going to extend page.
Now enable contributed module REST UI for managing REST resource as above module done.

REST resource is now plugin in Drupal 8. 
  • Plugins are small pieces of functionality that are swappable. 
  • Plugins which performs perform similar functionality are of the same type of plugin. 
  • In this case, we extend the ResourceBase plugin,

REST Resource with GET method

Expose existing nodes title in API of existing Drupal.
Create a resource file in resource folder firstcustommodule > src > Plugin > rest > resource
nodeTitlesGetRestResource.php.

To discover this custom rest resource by rest system, correctly written annotations are mandatory.
 Annotation for GET
/**
 * Provides REST API for nodes title.
 *
 * @RestResource(
 *   id = "get_nodes_title_rest_resource",
 *   label = @Translation("Nodes Title API"),
 *   uri_paths = {
 *     "canonical" = "/api/nodes/title"
 *   }
 * )
 */
Drupal Plugin manager will scan our class and see annotation is available for this plugin. This plugin is for rest resource of GET method.

<?php

/**
 * @file
 * Contains Drupal\firstcustommodule\Plugin\rest\resource\nodesTitleGetRestResource
 */

namespace Drupal\firstcustommodule\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides REST API for nodes title.
 *
 * @RestResource(
 *   id = "get_nodes_title_rest_resource",
 *   label = @Translation("Nodes Title API"),
 *   uri_paths = {
 *     "canonical" = "/api/nodes/title"
 *   }
 * )
 */
class nodesTitleGetRestResource extends ResourceBase {  
}

restui module provide the interface to manage REST resources. Go to admin > configuration > web service > REST.

With the above created code, you can see the created resource at page "/admin/config/services/rest" provided by restui module as shown in screenshot.
When we click on "Enable" button it will take us to its configuration page as shown in screenshot.
In this screenshot, Methods are missing because we have not implemented any method still now.
So now go to class  nodesTitleGetRestResource and write get() method. With this method, GET method is available to select while configuring rest resource.
class nodesTitleGetRestResource extends ResourceBase {
  /**
   * Responds to entity GET requests.
   *
   * @return \Drupal\rest\ResourceResponse
   *   Returning rest resource.
   */
  public function get() {
    return [];
  }
}
Now GET method will be available on resource configuration page as in screenshot. 
Check options as shown in image.
In Accepted request formats choose as per your requirement.
In Authentication providers, cookie option is available. Basic auth will come when we enable HTTP Basic Authentication module. 
Save configurations.






Full code for the above file.
<?php

/**
 * @file
 * Contains Drupal\firstcustommodule\Plugin\rest\resource\nodesTitleGetRestResource
 */

namespace Drupal\firstcustommodule\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides REST API for nodes title.
 *
 * @RestResource(
 *   id = "get_nodes_title_rest_resource",
 *   label = @Translation("Nodes Title API"),
 *   uri_paths = {
 *     "canonical" = "/api/nodes/title"
 *   }
 * )
 */
class nodesTitleGetRestResource extends ResourceBase {
  /**
   * Responds to entity GET requests.
   *
   * @return \Drupal\rest\ResourceResponse
   *   Returning rest resource.
   */
  public function get() {
    $nids = \Drupal::entityQuery('node')->execute();
    $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
    $node_titles = [];
    foreach ($nodes as $node) {
      $node_titles[$node->id()] = $node->getTitle();
    }
    return new ResourceResponse($node_titles);
  }
}
Save above file and hit URL: localhost/api/nodes/title/?_format=json.
Output will look like as in screenshot. 

Above created rest resource with get method.

No comments:

Post a Comment