Thursday, September 1, 2022

[SOLVED] Can you include raw JSON in Guzzle POST Body?

Issue

This should be soo simple but I have spent hours searching for the answer and am truly stuck. I am building a basic Laravel application and am using Guzzle to replace the CURL request I am making at the moment. All the CURL functions utilise raw JSON variables in the body.

I am trying to create a working Guzzle client but the server is respsonding with 'invalid request' and I am just wondering if something fishy is going on with the JSON I am posting. I am starting to wonder if you can not use raw JSON in the Guzzle POST request body? I know the headers are working as I am receiving a valid response from the server and I know the JSON is valid as it is currently working in a CURL request. So I am stuck :-(

Any help would be sooo greatly appreciated.

        $headers = array(
            'NETOAPI_KEY' => env('NETO_API_KEY'),
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'NETOAPI_ACTION' => 'GetOrder'
        );

    // JSON Data for API post
    $GetOrder = '{
        "Filter": {
            "OrderID": "N10139",
                "OutputSelector": [
                    "OrderStatus"
                ]
        }
    }';

    $client = new client();
    $res = $client->post(env('NETO_API_URL'), [ 'headers' => $headers ], [ 'body' => $GetOrder ]);

    return $res->getBody();

Solution

You can send a regular array as JSON via the 'json' request option; this will also automatically set the right headers:

$headers = [
    'NETOAPI_KEY' => env('NETO_API_KEY'),
    'Accept' => 'application/json',
    'NETOAPI_ACTION' => 'GetOrder'
];

$GetOrder = [
    'Filter' => [
        'OrderID' => 'N10139',
        'OutputSelector' => ['OrderStatus'],
    ],
];

$client = new client();
$res = $client->post(env('NETO_API_URL'), [
    'headers' => $headers, 
    'json' => $GetOrder,
]);

Note that Guzzle applies json_encode() without any options behind the scenes; if you need any customisation, you're advised to do some of the work yourself

$res = $client->post(env('NETO_API_URL'), [
    'headers' => $headers + ['Content-Type' => 'application/json'],
    'body' => json_encode($getOrders, ...),
]);


Answered By - Ja͢ck
Answer Checked By - Timothy Miller (WPSolving Admin)