How to send a POST request in JSON with Guzzle?

You can send a POST request with JSON data in Guzzle by passing in the JSON data as an array of key-value pairs via the json option.

Here is some sample code that sends a request to HTTP Bin with some sample JSON data:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('https://httpbin.org/post', [
    "json" => [
        'key1' => 'value1',
        'key2' => 'value2'
    ]
]);

echo $response->getBody();

// Output:
// {
//     "args": {},
//     "data": "{\"key1\":\"value1\",\"key2\":\"value2\"}",
//     "files": {},
//     "form": {},
//     "headers": {
//       "Content-Length": "33",
//       "Content-Type": "application/json",
//       "Host": "httpbin.org",
//       "User-Agent": "GuzzleHttp/7",
//       "X-Amzn-Trace-Id": "Root=1-63fa252d-60bf3c1b2258ff5903bdd116"
//     },
//     "json": {
//       "key1": "value1",
//       "key2": "value2"
//     },
//     "origin": "119.73.117.169",
//     "url": "https://httpbin.org/post"
// }

You can read more about it in the official Guzzle docs.

Related Guzzle web scraping questions: