json

Summary

The json option is used to easily upload JSON encoded data as the body of a request. A Content-Type header of application/json will be added if no Content-Type header is already present on the message.

Types

Any PHP type that can be operated on by PHP’s json_encode() function.

Default

None

Constant

GuzzleHttp\RequestOptions::JSON

  1. $response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);

Here’s an example of using the tap middleware to see what request is sent over the wire.

  1. use GuzzleHttp\Middleware;
  2. // Create a middleware that echoes parts of the request.
  3. $tapMiddleware = Middleware::tap(function ($request) {
  4. echo $request->getHeaderLine('Content-Type');
  5. // application/json
  6. echo $request->getBody();
  7. // {"foo":"bar"}
  8. });
  9. // The $handler variable is the handler passed in the
  10. // options to the client constructor.
  11. $response = $client->request('PUT', '/put', [
  12. 'json' => ['foo' => 'bar'],
  13. 'handler' => $tapMiddleware($handler)
  14. ]);

Note

This request option does not support customizing the Content-Type header or any of the options from PHP’s json_encode() function. If you need to customize these settings, then you must pass the JSON encoded data into the request yourself using the body request option and you must specify the correct Content-Type header using the headers request option.

This option cannot be used with body, form_params, or multipart