How to Use Guzzle to Send a Post Request in Json

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

For Guzzle <= 4:

It's a raw post request so putting the JSON in the body solved the problem

$request = $this->client->post(
$url,
[
'content-type' => 'application/json'
],
);
$request->setBody($data); #set body!
$response = $request->send();

Using Guzzle to send POST request with JSON

Give it a try

$response = $client->post('http://api.example.com', [
'json' => [
'key' => 'value'
]
]);

dd($response->getBody()->getContents());

Sending a POST request with JSON body using Guzzlehttp

The startpoint of the payload data should be an array in order to encode it to json. Otherwise you might encounter problems since you are then trying to encode data already in json format.

Step-1) Create a variable $payload where you store the data you wish to send with your request.

Step-2) Add body into your request (below headers), where $payload is your data, and json-encode the $payload.

'body'    => json_encode($payload)

To simplify the test you can also just add the pure text string.

'body' => json_encode('mydata goes here...')

Guzzle: Sending POST with Nested JSON to an API

I spent so many hours on this to just realise that products is actually expecting array of objects. I've been sending just a one-dimensional array and that was causing the 'Bad Request' error.

In order to fix this, just encapsulate 'vid' and 'quantity' into an array and voila!

How to send variable with the guzzle post method

Amount can pass in an array and after you can encode with json using ```json_encode``

Hope this works for you.

$amount = $request->get('amount');
$client = new \GuzzleHttp\Client();
$url = "http://192.168.150.16:7585/api/v1/Transaction/GetTransactionNumber";
$data = [
"amount" => $amount,
"something" => "1",
"description" => "desc",
];

$requestAPI = $client->post( $url, [
'headers' => ['Content-Type' => 'application/json'],
'body' => json_encode($data);
]);

Guzzle Request : Post body data

As per the linked answer, you need to pass the following options along with your request:

[GuzzleHttp\RequestOptions::JSON => ['key1' => 'value1', 'key2' => 'val2']] 

or:

['json' => ['key1' => 'value1', 'key2' => 'val2']]

But since you need to build your Request object first, you should be able to pass this option as the second parameter of Client::send:

$response = $client->send($request, [
GuzzleHttp\RequestOptions::JSON => ['key1' => 'value1', 'key2' => 'val2']
];


Related Topics



Leave a reply



Submit