Wednesday, February 16, 2011

Web Service Clients in PHP Part 1: POST to REST using a CURL client

The two most common types of web services are SOAP services and REST services. Today I will be talking about the latter. The most basic way to describe a RESTful service is that it is a URL that can be accessed through an http GET or POST (the author of the web service may only allow one or the other, or possibly both).

In my experience the easiest way to connect to a RESTful service is using CURL. I am going to show you a short and simple example here.

So you have just received an e-mail from a client with details on a web service they need to connect to. The information might look something like this:

Web Service URL: http://www.mywebservice.com/superduperfunction.php

POST variables: EmailAddress, FirstName, LastName, APIKey

Your APIKey: Eie73k08@12k

With a little help from CURL, connecting to this web service will be a piece of cake:

   // first we initialize an array and pre populate it with the
   // data we would like to post to the web service
   $postFields = array();
   $postFields['EmailAddress'] = 'fredflinstone@hannabarbara.com';
   $postFields['FirstName'] = 'Fred';
   $postFields['LastName'] = 'Flinstone';
   $postFields['APIKey'] = 'Eie73k08@12k';
   
   // now we are going to loop through our array and create a 
   // query string that we can actually post
   $varList = '';
   foreach ($postFields as $myKey => $myVal) {
      $varList .= $myKey.'='.urlencode($myVal).'&';
   }
   // strip the last & from the end of the query string
   $varList = substr($varList,0,-1);

   // now we initialize CURL, passing it the URL of the web service
   $ch = curl_init('http://www.mywebservice.com/superduperfunction.php');

   // follow redirects 
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);

   // dont return http headers
   curl_setopt($ch, CURLOPT_HEADER,0);

   // return the contents of the call
   curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);  
   
   // here we are telling CURL that we are using POST
   curl_setopt($ch, CURLOPT_POST,1);

   // now we load our query string 
   curl_setopt($ch, CURLOPT_POSTFIELDS,$varList);

   // actually post the data and save the response to a variable
   $response_data = curl_exec($ch);
  
   // close our CURL instance
   curl_close($ch);

   // here you could do whatever you need to do with the 
   // response from the web service
   

And there you have it ... Fred Flinstone is now a proud member of some neat new website, and all because you now know how to use CURL.

No comments:

Post a Comment