Let’s create something better together.

If you prefer phones, we have one of those too: +1 978 455 4515










    • Project Info
      icon
    • Technology
      icon
    • Contact Details
      icon







      BackNext








      Back

      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.

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

      rest ui configure drupal 8

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

      drupal 8 rest resources

       

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

      settings for resource content drupal

      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>

      <pre>
      $client =$this->http_client;
      $response = $client ->get('http://localhost/node/1?_format=json');
      $json_string =  json_decode($response->getBody());
      </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’]],
      ‘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
      ],
      ]);

      <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>

      <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 in Raleigh,USA 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.

      Author's Bio

      Jayesh Makwana
      Jayesh Makwana

      Jayesh Makwana writes with one goal in mind: to make Drupal easy for everyone. From his first steps with Drupal 6 to mastering the latest updates, he’s a true Drupal geek, passionate about sharing his knowledge. Whether it’s tips on Drupal migration, upgrading your site, or catching up on the newest features, Jayesh’s articles are your friendly guide. He simplifies complex topics, making them accessible to Drupal users of all levels. Follow Jayesh for insights that enlighten and inspire, all delivered with the enthusiasm of someone who loves what they do.

      Share This Article:

      Recent Blogs
      VIEW ALL BLOGS