I am using Guzzle to consume an API but for some reasons, I get this error:
http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given.
I don't know what I might be doing wrong. This is my code:
$data = ["name" => "joe doe"];
$jsData = json_encode($data);
$headers = [
'content-type' => 'application/json',
'Authorization' => "Bearer {$token}"
];
$call = $this->client->post(env('URL'),[
"headers" => $headers,
'form_params' => $jsData
]);
$response = json_decode($call->getBody()->getContents(), true);
Edit
$data = ["name" => "joe doe"];
$headers = [
'content-type' => 'application/json',
'Authorization' => "Bearer {$token}"
];
$call = $this->client->post(env('URL'),[
"headers" => $headers,
'form_params' => $$data
]);
$response = dd($call->getBody()->getContents(), true);
Client error: POST http://localhost/send
resulted in a 400 BAD REQUEST
response: { "error": { "code": 400, "message": "Failed to decode JSON object: No JSON object could be decoded", "u (truncated...)
The reason you're seeing the error is that form_params
should be an array
but you're running the array through json_encode
which returns a string:
$data = ["name" => "joe doe"];
$jsData = json_encode($data);
// ...
'form_params' => $jsonData
You should simply pass the data through as an array, without running it through json_encode
:
$data = ["name" => "joe doe"];
// ...
$call = $this->client->post(env('URL'), [
"headers" => $headers,
'form_params' => $data
]);