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.
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:
Filed under: CMS, PHP Tagged: Composer, Drupal, Drupal 8, Drupal Development, Guzzle, PHP, RESTful, Web Service