How to setup correct cURL request for X Post?

  api, curl, php

i have an api code to track the shipment, the api code is bellow ,

 curl -X POST 
     --header '17token:A967106205AA3133FCF520B4DE352161'
     --header 'Content-Type:application/json'
     --data '[{"number":"CM436202796IN"}]'
     https://api.17track.net/track/v1/register 

so i have created / copied a cURL code to fetch and output the data but i am getting {"code":0,"data":{"errors":[{"code":-18010013,"message":"Submitted data is invalid."}]}} error.

I think i am doing something wrong while sending data, here is my code.

<?php

// started curl
$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => "https://api.17track.net/track/v1/register",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => "number:CM436202796IN", // SOMETHING IS WRONG HERE.

    //data '[{"number":"CM436202796IN"}]'

    CURLOPT_HTTPHEADER => [
         "17token:A967106205AA3133FCF520B4DE352161",
         "header 'Content-Type:application/json"
        ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}
?>

I have tried all kind of data structures like :


 1. CURLOPT_POSTFIELDS => "CM436202796IN", 

 2. CURLOPT_POSTFIELDS => "[{number:CM436202796IN}]",
  
 3. CURLOPT_POSTFIELDS => "{number:CM436202796IN}",   
          
 4. CURLOPT_POSTFIELDS => '{number:CM436202796IN}',   
                
 5. CURLOPT_POSTFIELDS => '{number:CM436202796IN}',    
                    
 6. CURLOPT_POSTFIELDS => "data '[{number:CM436202796IN}]'",

 7. CURLOPT_POSTFIELDS => "{"number": "CM436202796IN"}",

 8. CURLOPT_POSTFIELDS => "[{"number": "CM436202796IN"}]",

but all the above "valid as php" requests are failing. and showing the same error.

CURLOPT_CUSTOMREQUEST => "X POST", is showing 400 bad request.

1. I think I am doing something wrong with X POST / POST or

2. I am failing to request

I am just started leaning PHP, so if you post the modified code it will help me to understand and solve the problem earlier.

Thank you.

Source: Ask PHP

LEAVE A COMMENT