php-guzzleHow to post a JSON body in PHP Guzzle?
Posting a JSON body in PHP Guzzle is easy. You can use the json
option in the request options array to set the body of the request.
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'http://example.com/api/v1/users', [
'json' => [
'name' => 'John Doe',
'email' => '[email protected]'
]
]);
The output of the above code will be a GuzzleHttp\Psr7\Response
object.
Code explanation
$client = new GuzzleHttp\Client();
- This creates a new Guzzle client.$response = $client->request('POST', 'http://example.com/api/v1/users', [
- This sends a POST request to the specified URL.'json' => [
- This sets the body of the request to a JSON object.'name' => 'John Doe',
- This sets the name field of the JSON object.'email' => '[email protected]'
- This sets the email field of the JSON object.
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- What version of PHP is required for Guzzle?
- How to make HTTP request with PHP Guzzle?
- How to stream with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
See more codes...