Monday, 15 September 2014

How to consume a REST/JSON webservice ?

In this post, I will give a way to consume a RESTFUL webservice, using the example given in the previous post for the webservice to be consumed :


 <?php

    $arg = '2';
    $function = 'double';
  
    //$function = 'doubleds';

    $base_url = 'http://localhost:8080/creation_service_rest.php';
    $query_string = '';
  
    $params = array (
        'function' => $function,
        'arg' => $arg,
    );
    //http://localhost/wp_phped/eros/eros/creation_service_rest.php?function=double&arg=2
  
    $query_string = get_urlrequest($params);

    $url = $base_url . "?" . $query_string;

  // $json =  file_get_contents($url);
   $content = URLToContent($url);

   $tab = json_decode($content, true);

 
   if (!empty($tab['response']['value'])) echo "Le double de $arg est ".$tab['response']['value'];
   else
   {
       if (!empty($tab['error']['code']))echo 'ERREUR : code '. $tab['error']['code'].' - '. utf8_decode($tab['error']['message']);
   }
 
 
    function URLToContent($url)
    {
        // create curl resource
        $curl = curl_init($url);

        curl_setopt($curl, CURLOPT_FAILONERROR, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($curl);

        //close curl resource to free up system resources
        curl_close($curl);  
        return $result;
    }

    function get_urlrequest($params) {
        $query_string = '';
        foreach ($params as $key => $value) {
            $query_string .= "$key=" . urlencode($value) . "&";
        }
        $query_string = substr($query_string,0,strlen($query_string) - 1);
      
        return $query_string;
      
     
    }
?>

This example is partly based on the one shown in  http://notos.fr/blog/index.php?article23/exemple-de-web-services-en-php

One could use instead the following functions to replace URLToContent and get_urlrequest functions, respectively:

function curl_get($url) {
      $client = curl_init($url);
      curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
     $response = curl_exec($client);
     curl_close($client);
     return $response;
}


function build_query_string(array $params) {
       $query_string = http_build_query($params);
       return $query_string;
}


The next step will be to include both functions in one include ( for example : RestFulWS.php ):

One Example with consuming an RSS feed from BBC news : 

 <?php
require_once 'RestFulWS.php';
$url = 'http://feeds.bbci.co.uk/news/rss.xml';

$response = curl_get($url);
$xml = simplexml_load_string($response);

echo $response;

foreach ($xml->channel->item as $item) {
echo $item->title . "\n";
}

Extracted from the book "RESTful PHP Web Services" by Samisa Abeysinghe, 2008

?>