how can call any REST API with PHP cURL Extension

how can call any REST API with PHP cURL Extension

, Writer

There are two methods to call REST API one is "GET" or "POST", you can call any type of API urls.

Use PHP cURL for API request and response is too easy.

Step: 1
Your Request array for API,

<?php 
$data = array (
  'HotelAvailability' => 
  array (
    'City' => 'Mumbai',
    'checkInDate' => '19/03/2018',
    'checkOutDate' => '20/03/2018',
    'adults' => 2,
    'children' => 2,
    'child_1_age' => 6,
    'child_2_age' => 6,
    'rooms' => 2,
  ),
);

?>

then after convert this associative array into JSON array using PHP function json_encode()  like,

$data_json = json_encode($data);

Step: 2

Now use PHP cURL for API call.

<?php 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'your api url');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
echo $response  = curl_exec($ch);
   //$new=var_dump(json_decode($response, true));
curl_close($ch);
?>

here complete working code which I use in my hotel booking web Application. 

create a file name "index.php",

<!DOCTYPE html>
<html>
<head>
  <title>
    Api Request
  </title>
</head>
<body>


<?php
$data = array (
  'HotelAvailability' => 
  array (
    'City' => 'Mumbai',
    'checkInDate' => '19/03/2018',
    'checkOutDate' => '20/03/2018',
    'adults' => 2,
    'children' => 2,
    'child_1_age' => 6,
    'child_2_age' => 6,
    'rooms' => 2,
  ),
);

$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'your api url');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
echo $response  = curl_exec($ch);
   //$new=var_dump(json_decode($response, true));
curl_close($ch);
?>

</body>
</html>

 


Comments / Answer

Leave a comment & ask question