How can I use Guzzle to send a POST request in JSON?

user3379466 picture user3379466 · Mar 7, 2014 · Viewed 257.9k times · Source

Does anybody know the correct way to post JSON using Guzzle?

$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'
        ),array(json_encode($_POST)));

I get an internal server error response from the server. It works using Chrome Postman.

Answer

Michal Gallovic picture Michal Gallovic · Apr 13, 2015

For Guzzle 5, 6 and 7 you do it like this:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);

Docs