Swapnil Shukla
Swapnil Shukla

Reputation: 3

Setting up CURL to receive a POST response from API

I am trying to create a php plugin to consume a API and receive a response while sending out the post request .

For the API , the header has to be set as Content-Type: application/x-www-form-urlencoded and the request object will be sent as request :{Json data} . I have tested it in Postman and I am receiving the response , but when trying to integrate it using php , getting the following error Missing parameter: request.

I am sharing the code and also the screenshots from Postman . Please help

<?php

$service_url = 'https://********/PostRequest';
$curl = curl_init($service_url);

//collection Object
$data = array(
    'request' => array(
        "Key1" => "*****",
        "key2" => "",
        "key3" => "****",
        "key4" => "****",
        "key5" => "****",
        "key6" => "****",
        "key7" => "***",
        "key8" => "****",
        "key9" => "***",
        "key10" => "****",
        "key11" => "***",
        "ItemList" => array(

            "subkey1" => "***",
            "subkey2" => "***",
            "subkey3" => "****",
            "subkey4" => "****",
            "subkey5" => "****",
            "subkey6" => "*****",
            "subkey7" => "***",
            "subkey8" => "***",
            "subkey9" => "***",
            "subkey10" => "**",
            "Subkey11" => "**",
            "subkey12" => "**",
            "subkey13" => "04",
            "subkey14" => "010101",
            "Subkey15" => "R",
            "Subkey16" => "70",
            "Subkey17" => array(
                "string" => "00"
            )
        ),
        "Address" => array(
            "PrimaryAddressLine" => "",
            "SecondaryAddressLine" => "",
            "County" => "",
            "City" => "",
            "State" => "",
            "PostalCode" => "****",
            "Plus4" => "",
            "Country" => "",
            "Geocode" => "",
            "VerifyAddress" => "false"
        ),
    )
);


 $data_json = json_encode($data);
// Set the CURLOPT_RETURNTRANSFER option to true
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// Set the CURLOPT_POST option to true for POST request
curl_setopt($curl, CURLOPT_POST, true);

// Set custom headers for RapidAPI Auth and Content-Type header
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); 

curl_setopt($curl, CURLOPT_POSTFIELDS, $data_json);

$response = curl_exec($curl);
curl_close($curl);

print_r($response);



die();

Screenshot from Postman:-

enter image description here

Upvotes: 0

Views: 84

Answers (1)

Barmar
Barmar

Reputation: 780663

Since the API requires URL-encoded data, you shouldn't encoded it as JSON. Use http_build_query() to convert the array to URL-encoded form.

curl_setopt(CURLOPT_POSTFIELDS, http_build_query($data));

Upvotes: 1

Related Questions