Can you include raw JSON in Guzzle POST Body?

Guzzle 7 Here

The below worked for me with raw json input

    $data = array(
       'customer' => '89090',
       'username' => 'app',
       'password' => 'pwd'  
    );
    $url = "http://someendpoint/API/Login";
    $client = new \GuzzleHttp\Client();
    $response = $client->post($url, [
        'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
        'body'    => json_encode($data)
    ]); 
    
    
    print_r(json_decode($response->getBody(), true));

For some reasons until I used the json_decode on the response, the output wasn't formatted.


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, ...),
]);