Can you include raw JSON in Guzzle POST Body? Can you include raw JSON in Guzzle POST Body? curl curl

Can you include raw JSON in Guzzle POST Body?


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


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 probably need to set the body mime type. This can be done easily using the setBody() method.

$request = $client->post(env('NETO_API_URL'), ['headers' => $headers]);$request->setBody($GetOrder, 'application/json');