How to POST and Receive JSON Data using PHP cURL in API?

PHP cURL is used to call api to get JSON Data by post and get method.

The following example makes an HTTP POST request and send the JSON data to URL with cURL in PHP.

  1. Specify the API URL ($apiurl) where the JSON data to be sent.
  2. Initiate new cURL resource using curl_init().
  3. Set data in PHP array and encode into a JSON string using json_encode().
  4. Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.
  5. Set the Content-Type of request to application/json using the CURLOPT_HTTPHEADER option.
  6. Return response as a string instead of outputting it using the CURLOPT_RETURNTRANSFER option.
  7. Finally the curl_exec() function is used to execute the POST request.

Example  :

<?
// API URL
$apiurl = 'http://www.aryatechno.com/?accessKey=**&secretKey=**';
 
//Create a new cURL resource
$ch = curl_init($apiurl);
$headers  = [
            'x-api-key: **********',
            'Content-Type: application/json'
        ];
        
//Setup request to send json via POST
 $postData = json_encode(array(
    "LookupName"=> "StatusCode",
"Operator" => "eq",
"LookupValue" => "0"
   )
);

/*echo $postData='{
"LookupName": "StatusCode",
"Operator": "eq",
"LookupValue": "0"
 
}';*/
  
//curl_setopt($ch, CURLOPT_URL,json_encode($apiurl));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    

//Set the content type to application/json       
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);

//Execute the POST request
$result = curl_exec ($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

//Close cURL resource
curl_close($ch);
 
if ( $status !== 201 || $status !== 200 ) {
   die("Error: call to URL failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
}
 
echo $result;
 

?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

96786