php-guzzleHow to make an HTTP POST request with JSON using PHP Guzzle?
Making an HTTP POST request with JSON using PHP Guzzle is easy. You can use the post() method of the Guzzle client to make a POST request. Here is an example code block:
$client = new GuzzleHttp\Client();
$response = $client->post('http://example.com/api/endpoint', [
'json' => [
'key1' => 'value1',
'key2' => 'value2'
]
]);
The output of the example code will be an instance of GuzzleHttp\Psr7\Response class.
Code explanation
$client = new GuzzleHttp\Client();- This creates a new Guzzle client instance.$response = $client->post('http://example.com/api/endpoint', [- This makes a POST request to the specified endpoint.'json' => [- This specifies that the request body should be in JSON format.'key1' => 'value1',- This is an example of a key-value pair that will be sent in the request body.]);- This closes the array and sends the request.
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to convert a Guzzle request to a cURL request in PHP?
- How to set a timeout for a request with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- How to send multiple requests with Guzzle in PHP?
- How to use PHP Guzzle to make a batch request?
- How to make HTTP2 request with PHP Guzzle?
- How to mock requests with Guzzle in PHP?
- How to use multipart/form-data with PHP Guzzle?
- How to send multipart requests with Guzzle in PHP?
See more codes...