1. Get your PHP client ready by following my previous post.
2. Update your index.php as follow.
<?php require 'vendor/autoload.php'; use Guzzle\Http\Client; use Guzzle\Plugin\Cookie\CookiePlugin; use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar; $cookiePlugin = new CookiePlugin(new ArrayCookieJar()); $client = new Client('http://drupal8.localhost.com'); $client->addSubscriber($cookiePlugin); $request = $client->post('user', null, array( 'name' => '<username>', 'pass' => '<password>', 'form_id' => 'user_login_form', )); $request->addHeader('Accept', 'application/json'); $response = $request->send()->json(); print '<pre>'; print_r($response); print '</pre>'; ?>
4. If it works, you can now always use the $client object for all future requests. For example, if you only allow authenticated user to access the content, the following piece of code will return you the corresponding node content.
<?php require 'vendor/autoload.php'; use Guzzle\Http\Client; use Guzzle\Plugin\Cookie\CookiePlugin; use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar; $cookiePlugin = new CookiePlugin(new ArrayCookieJar()); $client = new Client('http://drupal8.localhost.com'); $client->addSubscriber($cookiePlugin); $client->post('user', null, array( 'name' => '<username>', 'pass' => '<password>', 'form_id' => 'user_login_form', ))->send(); $request = $client->get('entity/node/1'); $request->addHeader('Accept', 'application/json'); $response = $request->send()->json(); print '<pre>'; print_r($response); print '</pre>'; ?>
5. An exception will be thrown without login or the login credential is incorrect.
Done =)
Reference: Drupal Community – REST: exposing data as RESTful web services
Filed under: CMS, PHP Tagged: Drupal, Drupal 8, Drupal Development, Guzzle, PHP, RESTful, Web Service