Reading:
Consuming REST API in PHP

Consuming REST API in PHP

Metamug
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.

This neat function is from Christoph Winkler's answer on Stackoverflow. It uses curl to send all REST requests.

function CallAPI($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, "username:password");

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

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

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 = CallAPI("GET","https://api.metamug.com/covid/v1.0/india");
$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; ?>
        </span>
    </h3>
  </div>
</div>

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.

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

Heavier payload is always better than more HTTP calls



Comments

Post a comment
Icon For Arrow-up