1

I've got those modules enabled:

  • HAL
  • HTTP Basic Authentication
  • JSON:API
  • REST UI
  • RESTful Web Services
  • Serialization

When I run this command, the content is created.

curl \
--user demo:9aqW72MUbFQR4EYh \
--header 'Accept: application/vnd.api+json' \
--header 'Content-type: application/vnd.api+json' \
--request POST http://www.demo.drupal/jsonapi/node/article \
--data-binary @payload.json

Now I try to read via PHP, which works fine too.

require 'vendor/autoload.php';

use GuzzleHttp\Client;

// Update to a user on your Drupal site that has permissions to create content
$user = 'demo';
$pass = '9aqW72MUbFQR4EYh';
$url = 'http://www.demo.drupal';

$content_client = new GuzzleHttp\Client([
    'base_uri' => $url,
    'timeout'  => 20.0,
]);

$res = $content_client->request('GET', '/jsonapi/node/mail/71adf560-044c-49e0-9461-af593bad0746');

$body = $res->getBody();
$stringBody = (string) $body;
var_dump(json_decode($stringBody, true));

I can't post content. The code I am using returns a 401, 402, or 500 error.

$headers = [
  'Content-type' => 'application/vnd.api+json',
  'Accept' => 'application/vnd.api+json'
];
$payload['data'] = [
  'type' => 'node--article',
  'attributes' => [
    "title" => "My custom title"
  ]
]; 

$guzzleResponse = $content_client->post('/jsonapi/node/article', [
  'json' => json_encode($payload),
  'headers' => $headers
]);

if ($guzzleResponse->getStatusCode() == 200) {
  $response = json_decode($guzzleResponse->getBody());
}

What am I doing wrong?

1 Answer 1

5

The 401 error is because you're not sending the basic auth creds like you are with your curl request. You need to add an Authorization header to your Guzzle request:

'Authorization' => 'Basic ' . base64_encode($user . ':' . $pass),

The 500 error is likely due to a malformed payload that JSONAPI can't parse. The value of json should be an associative array, not a JSON encoded string. See the Guzzle docs on uploading JSON data.

1
  • Thanks for pointing out the issues. I still had to change some details in the JSON payload, but now it's actually working. :)
    – Chris
    Commented Nov 13, 2020 at 3:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.