Skip to content

Instantly share code, notes, and snippets.

@Jaesin
Last active February 23, 2023 10:39
Show Gist options
  • Save Jaesin/898a0b74072c7573748b to your computer and use it in GitHub Desktop.
Save Jaesin/898a0b74072c7573748b to your computer and use it in GitHub Desktop.
Guzzle 4 in Drupal 8. Get a JSON version of a node.
<?php
// Example using cookie auth.
print (string) \Drupal::httpClient()
->get('http://example.com/node/1', [
'headers' => ['Accept' => 'application/json'],
'cookies' => ['SESS07e0668737e9f97189850d2cf0c79892' => 'dasGegKQ6ZzEF0xvRZWWzwrl9tt7UT8fGuXrAeLC9P1'],
])
->getBody(TRUE);
// Example using basic auth.
print (string) \Drupal::httpClient()
->get('http://example.com/node/1', [
'headers' => ['Accept' => 'application/json'],
'auth' => ['username', 'password'],
])
->getBody(TRUE);
// Creating a node.
$response = \Drupal::httpClient()
->post('http://example.com/entity/node', [
'timeout' => 120,
'auth' => ['admin', 'drupal'],
'body' => '{"type":[{"target_id":"article"}],"title":[{"value":"REST Create Node Test Title."}]}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]);
print_r($response);
// Using HAL
$response = \Drupal::httpClient()
->post('http://example.com/entity/node', [
// Username and password for HTTP Basic Authentication.
'auth' => ['admin', 'drupal'],
'body' => json_encode([
'title' => [['value' => 'Example node title']],
'type' => [['target_id' => 'article']],
'_links' => ['type' => ['href' => 'http://example.com/rest/type/node/article']],
]),
'headers' => [
'Accept' => 'application/hal+json',
'Content-Type' => 'application/hal+json'
],
])
->getStatusCode();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment