PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] Guzzle: Sending POST with Nested JSON to an API

 February 12, 2022     guzzle, php     No comments   

Issue

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


Solution

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!



Answered By - Hristijan Manasijev
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing