Connect Drupal 8 RESTful Service with Guzzle PHP Web Service Client @ 1

Previously I have setup a a Drupal 8 which is RESTful ready.

Guzzle is a PHP HTTP client & framework for building RESTful web service clients. In this example, we would create a simple .php to fetch a node from Drupal 8.

1. Make sure you have the Composer installed. You can refer to my previous post.

 

2. Create the composer.json in your webroot.

{
  "name": "eureka/test-composer",
  "require": {
    "php": ">=5.3.2",
    "guzzle/guzzle": "*"
  }
}

 

3. Download the dependencies by running the following command in shell.

composer install

 

4. Create the index.php.

<?php
  require 'vendor/autoload.php';
  use Guzzle\Http\Client;

  $client = new Client('http://drupal8.localhost.com');
  // If in a Drupal environment use the HTTP client service.
  //$client = Drupal::httpClient()->setBaseUrl(''<server url>');

  $request = $client->get('entity/node/1');
  $request->addHeader('Accept', 'application/json');
  $response = $request->send()->json();

  print '<pre>';
  print_r($response);
  print '</pre>';
?>

 

5. Open the index.php in browser and check if your RESTful call works or not.
simple-guzzle-client-1
 

6. Again, you could get a JSON in HAL response by modifying your request header. This is required in POST request for Drupal 8.

<?php
  require 'vendor/autoload.php';
  use Guzzle\Http\Client;

  $client = new Client('http://drupal8.localhost.com');
  // If in a Drupal environment use the HTTP client service.
  //$client = Drupal::httpClient()->setBaseUrl('<server url>');

  $request = $client->get('entity/node/1');
  $request->addHeader('Accept', 'application/hal+json');
  $response = $request->send()->json();

  print '<pre>';
  print_r($response);
  print '</pre>';
?>

 

Done =)

Reference:

Advertisement

3 thoughts on “Connect Drupal 8 RESTful Service with Guzzle PHP Web Service Client @ 1”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.