0

I've got this CURL that I'm executing on the command line and it successfully creates content in my CMS (Drupal 9).

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

and the JSON file as:

{
  "data": {
    "type": "node--article",
    "attributes": {
      "title": "My custom title",
      "body": {
        "value": "Custom value",
        "format": "plain_text"
      }
    }
  }
} 

Working like a charm and data is being created. I've been trying to do this in GuzzleHttp but couldn't get it working.

Get is working: require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

$url = 'http://www.domain.drupal';

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

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

For POST, I've got probably around 10 versions trial and error but nothing worked. How can I POST my JSON/Content to Drupal or how can I correctly implement the CURL in Guzzle?

bhucho
  • 3,903
  • 3
  • 16
  • 34
Chris
  • 1,265
  • 4
  • 18
  • 37

1 Answers1

0

If you want a simple post request to send json body with your headers you can do it simply without using Psr7 Request. Guzzle utilizes PSR-7 as the HTTP message interface.

use GuzzleHttp\Client;

$url = 'http://www.domain.drupal';

$content_client = new Client([
    'base_uri' => $url,
    'timeout'  => 20.0,
]);
$headers = [
    'Content-type' => 'application/vnd.api+json',
    'Accept' => 'application/vnd.api+json'
];
$payload['data'] = [
        'type' => 'node--article',
        'attributes' => [
                "title" => "My custom title",
                "body" => [
                        "value" => "Custom value",
                        "format" => "plain_text"
                    ]
            ]
    ]; 
$guzzleResponse = $content_client->post('/jsonapi/node/article/71adf560-044c-49e0-9461-af593bad0746', [
                'json' => json_encode($payload),
                'headers' => $headers
            ]);

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

You can write it in try catch block with using RequestException (see this Catching exceptions from Guzzle to know more about it.)

bhucho
  • 3,903
  • 3
  • 16
  • 34