GET A QUOTE

Integrate REST webservice using Guzzle in Drupal 8

Drupal 8 Core includes Restful Web Service module. It builds from Drupal 7 Restful Web Service below are the basic points of the REST in Drupal 8. For the purpose of this article, all the screenshots are for 8.3.x.

REST in Drupal 8:

REST is one of the many options Drupal offers to manage content of websites. It uses HTTP methods to manage operation. It depends on Drupal core’s serialization module. REST allows us to manage any entity of the system.

REST Request Fundamentals:

1. Read Only Methods: GET, HEAD, OPTIONS, TRACE are read only methods. It do not require authentication process.
2. Write/Manage Only Methods: POST, PUT, DELETE, CONNECT, PATCH methods require authentication process for managing data. X-CSRF-token is used for restricting against CSRF attack. You can acquire it from localhost/session/token URL. We must require _format query argument for REST request.

Requirements to enable REST:

1. Install (Restlet Client – REST API Testing) addon in chrome extension for verification purpose.
2. Install RestUI module (https://www.drupal.org/project/restui)
3. Install drupal’s core modules ( HAL, HTTP Basic Authentication, RESTful Web Services, Serialization). You can install it by clicking on Extends link from admin screen.

Steps to manage node data through REST:

1. Access http://localhost/admin/config/services/rest for listing all links of REST UI.

Click on configure link, you will see the following screen. Please click on Edit link for configuration of this link.

After that, you will see following configuration for that specific REST.

Dependency Injection for accessing http_client service:

I have created dependency injection for accessing http_client for Client of Guzzle. I have provided you example based on configuration of FORM.

Include namespace in your file (FORM file).

<pre>
use GuzzleHttp\Client;
</pre>

Declare private variable in class file.

<pre>
private $http_client;
</pre>

Assign Client to http_client variable in _construct method of class. Use below code for assigning Client to private http_client variable.

public function __construct(Client $http_client) {
    $this->http_client = $http_client;
  }

Access http_client service. Use below method for accessing http_client service.

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('http_client')
    );
  }
Use below code to assign http_client to $client variable.
<pre>
$client =$this->http_client;
</pre>

1. GET request: You can get node detail page using following code.

<pre>
$client =$this->http_client;
$response = $client ->get('http://localhost/node/1?_format=json');
$json_string =  json_decode($response->getBody());
</pre>

2. POST request: You can add node using X-CSRF token.

/* Get Session Token Start Code */
  $client =$this->http_client;
  $response = $client
    ->get('http://localhost:8888/drupal-8.3.4/rest/session/token');
   $token_string =  (string) ($response->getBody()) ;
  /* Get Session Token End Code*/


 $serialized_entity = json_encode([
      'title' => [['value' => 'Example Article']],
      'type' => [['target_id' => 'article']],
      '_links' => ['type' => [
          'href' => 'http://localhost/rest/type/node/article'
      ]],
    ]);

$response = $client
    ->post('http://localhost/entity/node?_format=hal_json', [
      'auth' => ['user', 'password’],
      'body' => $serialized_entity,
      'headers' => [
        'Content-Type' => 'application/hal+json',
        'X-CSRF-Token' => $token_string
      ],
    ]);

3. Update Request: You can update details of node id = 1 using following code.

<pre>

/* Get Session Token Start Code */
  $client =$this->http_client;
  $response = $client
    ->get('http://localhost:8888/drupal-8.3.4/rest/session/token');
   $token_string =  (string) ($response->getBody()) ;
  /* Get Session Token End Code*/


$serialized_entity = json_encode([
  'title' => [['value' => 'Example Article UPDATED']],
  'type' => [['target_id' => 'article']], 
  '_links' => ['type' => [
      'href' => 'http://localhost/rest/type/node/article'
  ]],
]);

$response = $client
  ->patch('http://localhost/node/1?_format=hal_json', [
    'auth' => ['user', 'password’],
    'body' => $serialized_entity,
    'headers' => [
      'Content-Type' => 'application/hal+json',
      'X-CSRF-Token' => $token_string
    ],
  ]);

</pre>

4. Delete request: You can delete node = 1 using following code.

<pre>

/* Get Session Token Start Code */
  $client =$this->http_client;
  $response = $client
    ->get('http://localhost/rest/session/token');
   $token_string =  (string) ($response->getBody()) ;
  /* Get Session Token End Code*/

$response = $client
  ->delete('http://localhost/node/1?_format=hal_json', [
    'auth' => ['user', 'password’],
     'headers' => [
      'X-CSRF-Token' => $token_string
    ],
  ]);

</pre>

Hope you have found an easy solution to access your data using the REST in Drupal 8? There are many more easy way outs to access your Drupal 8 in an easy manner, for further solutions stay tuned as we have many more blogs in process. cmsMinds is a leading Drupal development company have team of drupal developers, to assist you on simple to challenging projects. We are also the privileged members at drupal.org. Please visit us on Drupal.org for our current active participation notes.

Save

Leave a Reply

Your email address will not be published. Required fields are marked *

Quick Inquiry


captcha