Using curl to make REST API calls

My preferred method to make REST calls from PHP is using curl; a REST GET call is nothing more than just fetching a file sitting on a web server. PHP supports it as long as the libcurl package is installed on your system and PHP is compiled with the curl option.

The following curl wrapper class is to make our life little easier when making calls to REST API. You can use curl functions directly, but I found the code to be verbose with all the error handling and status checks that go with each call, which can overwhelm someone reading the code, including you when you come back to your code to make some change or fix something.

CurlWrap.php

<?php

   define('CURL_EXEC_RETRY_MAX',3);

   class CurlWrap
   {
      private $ch;
      private $url;
      private $response;
      private $info;
      private $http_code;

      function __construct()
      {
         $this->ch = curl_init();
         $this->setOption(CURLOPT_RETURNTRANSFER,true);
         $this->setOption(CURLOPT_BINARYTRANSFER,true);
         $this->setOption(CURLOPT_FOLLOWLOCATION,true);
      }

      function __destruct() {curl_close($this->ch); }

      public function setOption($option,$value) {curl_setopt($this->ch,$option,$value);}

      public function exec($url='')
      {
         if ($url!='') $this->setOption(CURLOPT_URL,$url);
         $this->retryExec();
         $this->info=curl_getinfo($this->ch);
         $this->http_code=$this->info['http_code'];
      }

      public function getHttpCode() {return $this->http_code;}
      public function getExecResponse() {return $this->response;}
      public function getExecInfo() {return $this->info;}
      public function getError() {return curl_error($this->ch);}

      //The logic of retry can be different, but when making a web service call
      //it is essential have some retry, as the resource might not be accessible briefly online
      //due to many reasons.
      private function retryExec()
      {
         $i=0;
         while ($i++ <CURL_EXEC_RETRY_MAX) {
            $this->response=curl_exec($this->ch);
            if ($this->response) break;
            if ($i<CURL_EXEC_RETRY_MAX) sleep($i);
         }
      }

   }
?>

Using CurlWrapper class

Using this class making curl calls from your PHP code would be very easy. Look at this sample program, which fetches the RSS feed for the most E-Mailed articles.

test_curlwrap.php

<?php

include_once 'CurlWrap.php';

$curl=new CurlWrap();
$curl->exec("http://www.nytimes.com/services/xml/rss/nyt/pop_top.xml");
if ($curl->getHttpCode()!='200')  print "ERROR: Failed to fetch url. ". $curl->getError(). "\n";
else print $curl->getExecResponse();

?>

This will just print out the RSS feed.

Now, try changing the domain to something non-existent, like http://www.xxnytimes.com. Then you will see an error message like this:
ERROR: Failed to fetch url. Couldn’t resolve host ‘www.xxnytimes.com’

The default HTTP request method used by curl is GET, and that’s what we used in the last example. REST API’s typically use GET for reads, POST for creating a new entry, and PUT for updating an existing entry. In such cases, related options must be set prior to making call to the API. We will learn such things in later posts where I will describe how your PHP app can be integrated with Twitter.

About these ads
This entry was posted in PHP. Bookmark the permalink.

4 Responses to Using curl to make REST API calls

  1. Pingback: Fetching RSS Feeds | Smooth Operator

  2. Pingback: Shortening URL Using bit.ly Web Service API | Smooth Operator

  3. Pingback: Integrating apps with Twitter | Smooth Operator

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s