Hristijan Manasijev
Hristijan Manasijev

Reputation: 73

Guzzle: Sending POST with Nested JSON to an API

I am trying to hit a POST API Endpoint with Guzzle in PHP (Wordpress CLI) to calculate shipping cost. The route expects a RAW JSON data in the following format:

{
   "startCountryCode": "CH"
   "endCountryCode": "US",
   "products": {
       "quantity": 1,
       "vid": x         //Variable ID
    }
}

Link to the API I am consuming: https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate

$body = [
     "endCountryCode"    => "US",
     "startCountryCode"  => "CN",
     "products"          => [
             'vid'               => $vid,
             'quantity'          => 1
     ],
 ];

 $request = $this->client->request(
     'POST', 'https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate',
     [
         'headers' => [
                'CJ-Access-Token' => $this->auth_via_cj(), // unnecessary, no auth required. Ignore this header
         ],
         'body' => json_encode( $body )
     ],
);

I've also tried using 'json' => $body instead of the 'body' parameter.

I am getting 400 Bad Request error.

Any ideas?

The Guzzle exception I am getting

Upvotes: 0

Views: 760

Answers (3)

Hristijan Manasijev
Hristijan Manasijev

Reputation: 73

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!

Upvotes: 1

Girish Latkar
Girish Latkar

Reputation: 11

Try to give body like this.

"json" =>  json_encode($body)

Upvotes: 1

onkar.am
onkar.am

Reputation: 600

You don't need to convert data in json format, Guzzle take care of that. Also you can use post() method of Guzzle library to achieve same result of request. Here is exaple...

$client = new Client();
$params['headers'] = ['Content-Type' => 'application/json'];
$params['json'] = array("endCountryCode" => "US", "startCountryCode" => "CN", "products" => array("vid" => $vid, "quantity" => 1));
$response = $client->post('https://developers.cjdropshipping.com/api2.0/v1/logistic/freightCalculate', $params);

Upvotes: 0

Related Questions