I am trying to consume a POST api with Guzzle, after testing that it works on Postman:
https://snipboard.io/Bqwd5y.jpg
As you can see, there is a body which is an array of objects.
With Guzzle I tried this. First I converted that payload to a php array:
$body = [
[
"Url" => "StorageMgmt",
"Method" => "PATCH",
"Payload" => [
"Identities" => [
"userId" => "userid",
"companyId" => "company",
"ownerId" => "ownerId",
],
],
],
[
"Url" => "Reports/List",
"Method" => "GET",
],
];
Then I set it as the POST body, I tried different ways:
$promise = $this->httpClient->postAsync($url, [
'json' => $body, // did not work, server responded with 500 error
//'body' => $body // did not work
//'body' => json_encode($body), // did not work, server responded with 500 error
])
->then(
function (ResponseInterface $resp) {
$jsonBody = json_decode($resp->getBody(), true);
return $jsonBody;
},
function (RequestException $ex) {
parent::handleHttpException($ex);
}
);
return $promise->wait();
After a lot of testing, the only way that it works is quite weird to me, because it is to pass the array as plain text, such as:
$promise = $this->httpClient->postAsync($url, [
'body' => '[
{
"Url": "StorageMgmt",
"Method": "PATCH",
"Payload": {
"Identities": {
"userId": "userid",
"companyId": "company",
"ownerId": "ownerId"
}
}
},
{
"Url": "Reports/List",
"Method": "GET"
}
]',
])
->then(
function (ResponseInterface $resp) {
$jsonBody = json_decode($resp->getBody(), true);
return $jsonBody; // returned by $promise->wait()
},
function (RequestException $ex) {
parent::handleHttpException($ex);
}
);
return $promise->wait();
}
And the trick is to avoid IDE auto-formatting, which means no extra spaces, not tabs etc in the body string.
Can someone help me understand why it works this way? Shouldn't I be able to just pass the array or the json_encode of it?
How can I replicate with Guzzle what I have working in Postman?
Thanks.
PS: I do set the Accept and Content-Type to application/json. I just omitted them from the code snippet to keep it more readable.