I have created an API request, it connects to the server fine and passes basic authentication. The error I receive is
“Uncaught GuzzleHttpExceptionClientException: Client error:
POST http://my.api.com/dest/addrresulted in a400 Bad Requestresponse: {“code”:400,”result”:”Missing customer id”
I have tried many ways to pass the query parameters and none of them have worked. I checked to make sure the JSON being output was formatted correctly. I have followed the directions in the Guzzle documentation. I have also tried every solution I could find in the forums and none of them gave me a different response. I am not sure what I am missing, hoping someone can see what the problem might be… I have pasted what I feel is the code that best follows the Guzzle documentation below. Thanks.
<?php
require __DIR__.'/../vendor/autoload.php';
use GuzzleHttpClient;
use GuzzleHttpExceptionRequestException;
Use GuzzleHttpPsr7;
try {
$client = new Client(['base_uri' => 'http://my.api.com/']);
$credentials = base64_encode('12345');
$request_param = [
'json' => [
'customer' => [
'name' => 'Mary',
'id' => 111
],
'products' => [
[
'product_id' => 2,
'qty' => 3
]
]
]
];
$request_data = json_encode($request_param, true);
$headers = ['headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Basic ' . $credentials
]];
$response = $client->request('POST', 'dest/addr', $headers, $request_data);
echo $response->getStatusCode();
echo "<br />";
echo $response->getHeader('content-type')[0];
echo "<br />";
echo "<pre />";
echo $response->getBody()->getContents();
}
catch(GuzzleHttpExceptionClientException $e) {
echo $e->getCode(). '<hr />';
echo $e->getMessage();
}
//Server Exception
catch(GuzzleHttpExceptionServerException $e) {
echo $e->getCode(). '<hr />';
echo $e->getMessage();
}
Advertisement
Answer
if your my.api.com can accept json request(not form params json=json_string&something=value in post body).you could try like this
$json_data = [
'customer' => [
'name' => 'Mary',
'id' => 111
],
'products' => [
[
'product_id' => 2,
'qty' => 3
]
]
];
$headers = [
'Authorization' => 'Basic ' . $credentials
];
$response = $client->request('POST', 'dest/addr', [
'json' => $json_data,
'headers' => $headers
]);