Skip to content

Instantly share code, notes, and snippets.

@blainelang
Last active July 17, 2017 12:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blainelang/46353455dbaf53499c58 to your computer and use it in GitHub Desktop.
Save blainelang/46353455dbaf53499c58 to your computer and use it in GitHub Desktop.
Drupal 8 standalone PHP script using Guzzle to request a node with a JSON response and HTML response.
<?php
/* Script located in the docroot for your Drupal 8 site */
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
$autoloader = require_once __DIR__ . '/core/vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
echo '<h1>RESTful request to get a json response for node 1</h1>';
$request = $client->createRequest('GET', 'http://localhost/d8test2/node/1');
// Set the Accept header for the D8 JSON representation
$request->setHeader('Accept', 'application/hal+json');
$response = $client->send($request);
$json = $response->json();
echo '<pre>' . var_dump($json) . '</pre><hr>';
// Now display just the node body value
echo '<h1>Node 1 body value</h1>';
print $json['body'][0]['value'];
echo '<h1>Retrieve the complete site</h1>';
$response = $client->get('http://localhost/d8test2/node/1');
$body = $response->getBody();
// By default if the response is large, Guzzle will save the body in a temp file
while (!$body->eof()) {
echo $body->read(1024);
}
@ykarthikvarma
Copy link

Hi,

Thanks for the clear example of requesting node data from json response. But while I was trying out I am stuck at the following error

TypeError: Argument 3 passed to GuzzleHttp\Client::request() must be of the type array, string given, called in C:\xampp\htdocs\services\vendor\guzzlehttp\guzzle\src\Client.php on line 87 in GuzzleHttp\Client->request() (line 126 of C:\xampp\htdocs\services\vendor\guzzlehttp\guzzle\src\Client.php).

I tried to search for the fix and no luck yet. Could you please help me out in this !

Thanks
Karthik

@blainelang
Copy link
Author

Drupal updated the guzzle version to 6.x during the beta13 release and the API changed - https://www.drupal.org/node/2536856

@jbfelix
Copy link

jbfelix commented Apr 28, 2017

Then how to fix this script ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment