Skip to content
Advertisement

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’ parametar.

I am getting 400 Bad Request error.

Any ideas?

The Guzzle exception I am getting

Advertisement

Answer

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!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement