6CS028 Workshop - Web Services

From mi-linux
Revision as of 16:29, 14 October 2009 by In9352 (talk | contribs)
Jump to navigationJump to search

Main Page >> Web Application Development >> Workbook >> Week 07

There are so many exciting APIs available on the web that it is impossible to cover them all here… so let’s have a look at a known REST example and a known SOAP example:

  • REST - The Wikipedia API
  • SOAP - The Google Search API
  • A challenge for you!

REST - The Wikipedia API

All features shown on this page should be working, but the API is still in active development, and may change at any time. Make sure to monitor their mailing list for any updates.

Let’s simply find all all the Wikipedia pages that link to my website www.bdtheque.com :o)

With REST, it's all about calling the right URL, passing in the right parameters... here is the URL we need:

Click me!

If you click on the URL, your browser simply display the XML data (try looking at the page's source code).

So our PHP code looks very much like the code we used to access an RSS feed. Indeed in both cases we are accessing a remote XML file!

<?

  $url = "http://en.wikipedia.org/w/api.php?"
        ."action=query&"
        ."list=exturlusage&"
        ."format=xml&"
        ."euquery=www.bdtheque.com";
          
  // Get raw data
  $response = file_get_contents($url);
  
  // Convert raw data to object
  $xml = simplexml_load_string($response);
 
  // Loop through data and display
  foreach($xml->query->exturlusage->eu as $link)
  {
    echo "<H1>{$link['title']}</H1><P>Links to: {$link['url']}</P>";
  }  

?>

And that’s it! Your page should now be displaying all the Wikipedia pages that link to my website www.bdtheque.com.

A SOAP example: Google Search

Accessing SOAP APIs is just as simple. But first you need to download the NuSOAP library. It will do a lot of the work for you.

Simply unzip the archive in your web pages’ folder.

Now the code… well nothing too difficult here:

  • First you include the library you have just downloaded
  • Then you create a SOAP client object and set its encoding
  • Then you prepare your SOAP request and send it.
  • The response is a multidimensional array. You can use the print_r command to display it fully if you wish.
<?
  require("nusoap/lib/nusoap.php");

  // What we are searching for
  $search = "Alix Bergeret";

  // Create soap client
  $client = new soapclient("http://api.google.com/GoogleSearch.wsdl", true);

  // Set encoding
  $client->soap_defencoding = 'UTF-8';

  // Prepare request
  $request = array(
		'key'=>'4B0KufpQFHJxhAxzua0tR11ElLNrHRJ6',
		'q'=>$search,
		'start'=>0,
		'maxResults'=>5,
		'filter'=>false,
		'restrict'=>'',
		'safeSearch'=>true,
		'lr'=>'',
		'ie'=>'',
		'oe'=>'',
	);

  // Send request and read response
  $result = $client->call('doGoogleSearch', $request, "urn:GoogleSearch", "urn:GoogleSearch");

  // Loop through array and display
  foreach($result['resultElements'] as $one_result)
  {
    print "<h1>{$one_result['title']}</h1>";
    print "<p>{$one_result['snippet']}</p>";
  }
?>

All done!

A challenge for you!

The Amazon “Product Advertising API” is one of the most exciting ones available, as it gives you free access to the huge Amazon catalogue, as well as some cool functionalities (searches, similar products, customer reviews etc)

Unfortunately it became a lot harder to access it on 15th August 2009, as Amazon now requires all requests to be signed and time stamped.

I have spent a couple of hours trying to get the top selling books from Amazon.com via a REST request, but failed miserably. I get the following error message:

“xxx is not a valid value for Signature. Please change this value and retry your request.”

I have included my code so far (you will need to get your own account, with a public and a private key), and a few useful links.

Have a go! The first student to get it to work will win my gratitude and uttermost respect, as well as a free copy of a brand new book entitled “Web 2.0 architectures”. Exciting stuff! (where’s the geeky smiley on this thing?)

Useful links:

My code so far:

<?

  $secret_key = 'Your own secret key here';

  //---------------------------------------------------------------
  // List of parameters
  //---------------------------------------------------------------
  $param_string = "AWSAccessKeyId=Your own public key here"
                 ."&BrowseNodeId=283155"
                 ."&Operation=BrowseNodeLookup"
                 ."&ResponseGroup=TopSellers"
                 ."&Service=AWSECommerceService"
                 ."&Timestamp=".urlencode(date("Y-m-d\TH:i:s\Z"))
                 ."&Version=".urlencode('2009-01-06');

  //---------------------------------------------------------------
  // Build signature
  //---------------------------------------------------------------
  $signature = "GET\n";
  $signature.= "webservices.amazon.com\n";
  $signature.= "/onca/xml\n";
  $signature.= $param_string;

  //---------------------------------------------------------------
  // Hash and url encode signature
  //---------------------------------------------------------------
  $signature = hash_hmac('sha256', $signature, $secret_key);
  $signature = urlencode($signature);

  //---------------------------------------------------------------
  // Add signature to parameters
  //---------------------------------------------------------------
  $param_string = $param_string."&Signature=".$signature;
  
  //---------------------------------------------------------------
  // Build URL
  //---------------------------------------------------------------
  $url = "http://webservices.amazon.com/onca/xml?$param_string";

  //---------------------------------------------------------------
  // Get raw data
  //---------------------------------------------------------------
  $response = file_get_contents($url);
  print("$response");

  //---------------------------------------------------------------
  // Convert raw data to object
  //---------------------------------------------------------------
  $xml = simplexml_load_string($response);
 
  // Browse object and display book titles
  foreach($xml->BrowseNodes->BrowseNode->TopSellers->TopSeller as $book)
  {
    echo $book->Title."<br>";
  }

?>