Consuming REST API in PHP

Consuming REST API in PHP

Consuming REST API in PHP

Using Curl for calling APIs

We all know about curl. PHP has a library for curl. We need to install it before we can use it in php.

sudo apt-get install php5-curl
sudo service apache2 restart

After installing restart the apache server for curl to take effect.

function rest_call($method, $url, $data = false, $contentType= false, $token = false)
    $curl = curl_init();

    if($token){ //Add Bearer Token header in the request
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Authorization: '.$token

    switch ($method)
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data){
                    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                        'Content-Type: '.$contentType
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);


    return $result;

Sending URL Encoded FORM POST Request

$postData = array("name"=>"John Doe", "from"=>"New York");
$string = http_build_query($postData);
$url = '';
$jsonResponse = rest_call("POST",$url, $string, 'application/x-www-form-urlencoded');
$response = json_decode($jsonResponse);

Sending JSON in PHP POST Request

When sending the request as JSON data, Content-Type header needs to be set as application/json. Store the data in a php array and use json_encode function to convert it into JSON String to be passed in the request body.

$postData = array("name"=>"John Doe", "from"=>"New York");
$jsonData = json_encode($postData);
// Send the request
$url = '';
$jsonResponse = rest_call('POST',$url, $jsonData,'appplication/json');

//Decode json back to PHP object
$response = json_decode($jsonResponse);

The JSON returned in the response is converted back to PHP object, using json_decode. The below example shows how to use JSON returned in the response.

Server side rendering with JSON in PHP

So once we call our REST API, we want to use the JSON on the server-side to render the html.

$covidJsonResponse = rest_call("GET","");
$covidIndiaObject = json_decode($covidJsonResponse);
$lastCovidUpdateInfo = end($covidIndiaObject->historical_count);

As you can see the json_decode method is gives us a jsp object, which will help in server side rendering. If this REST API call was made from the browser, to update a div with the json values we would require dom manipulation.

<div class="card col-md-4">
  <div class="card-body">
    <h3><span class="badge badge-success" id="cured_count">
            <?php echo $lastCovidUpdateInfo->total_cured_count; ?>

After the DOM is rendered on the client side, we are required to change using javascript. In this case, we can have the same ease of accessing the json object and its attributes without the DOM manipulation.

Passing the JSON to Javascript from PHP

There are cases we would like to send this JSON down to the browser like charting and for the user of js libraries that php can't handle. We can make the JSON we retrieved using our REST call in php to the javascript. During the initial page load, this json will be passed in the DOM. Client side rendering is faster as it can avoid the HTTP call to fetch the JSON.

    var covidJsonResponse = <?php echo $covidJsonResponse ?>;

Heavier payload is always better than more HTTP calls


Post a comment
Icon For Arrow-up