Difference between revisions of "6CS028 Workshop - Web Services"

From mi-linux
Jump to navigationJump to search
Line 1: Line 1:
 
[[Main Page]] >> [[6CS028|Advanced Web Development]] >> [[6CS028 - Workbook|Workbook]] >> Week 05
 
[[Main Page]] >> [[6CS028|Advanced Web Development]] >> [[6CS028 - Workbook|Workbook]] >> Week 05
 
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 REST example and a SOAP example.
 
  
 
== REST - The Wikipedia API ==
 
== REST - The Wikipedia API ==
 
All features shown on [http://en.wikipedia.org/w/api.php 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 [http://www.bdtheque.com www.bdtheque.com] :o)
 
Let’s simply find all all the Wikipedia pages that link to my website [http://www.bdtheque.com www.bdtheque.com] :o)
Line 21: Line 17:
 
If you click on the URL, your browser simply display the XML data (try looking at the page's source code).
 
If you click on the URL, your browser simply display the XML data (try looking at the page's source code).
  
Here is the PHP code to read and process the XML data:
+
=== The controller ===
  
 +
Create a '''new Apis.php'' controller:
 
<pre>
 
<pre>
<?
+
<?php
 
 
  // Since 2010 a user agent is required
 
  ini_set('user_agent', 'University of Wolverhampton');
 
  
  $url = "http://en.wikipedia.org/w/api.php?"
+
namespace App\Controllers;
        ."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>";
 
  }         
 
  
?>
+
use App\Models\NewsModel;
</pre>
 
  
And that’s it! Your page should now be displaying all the Wikipedia pages that link to my website www.bdtheque.com.
+
class Apis extends BaseController
 +
{
 +
public function wikipedia()
 +
{
 +
// Since 2010 a user agent is required
 +
ini_set('user_agent', 'University of Wolverhampton');
  
Here's a working example on [https://mi-linux.wlv.ac.uk/~in9352/apis/wikipedia.php my account].
+
$website = "www.bdtheque.com";
  
== A SOAP example: Flickr Search ==
+
$url = "http://en.wikipedia.org/w/api.php?"
 +
."action=query&"
 +
."list=exturlusage&"
 +
."eulimit=500&"
 +
."format=xml&"
 +
."euquery=".$website;
 +
 
 +
// Get data from URL and store in object
 +
$data['links'] = simplexml_load_file($url);
 +
$data['title'] = "Wikipedia API";
  
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. Get the latest version from here:
+
echo view('templates/header', $data);
 
+
echo view('apis/wikipedia', $data);
* [http://sourceforge.net/projects/nusoap/files/nusoap/ http://sourceforge.net/projects/nusoap/files/nusoap/]
+
echo view('templates/footer', $data);
 
+
}
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.
 
 
 
The Flickr SOAP API documentation is here:
 
* [http://www.flickr.com/services/api/request.soap.html http://www.flickr.com/services/api/request.soap.html]
 
 
 
<pre>
 
<?
 
  require("nusoap/lib/nusoap.php");
 
 
 
  // Create soap client
 
$client=new nusoap_client("http://api.flickr.com/services/soap/");
 
 
 
  // Set encoding
 
$client->soap_defencoding = 'UTF-8';
 
 
 
  // Prepare request
 
$request=array(
 
'api_key'=>'489ef07aabc7de443750a542058090bf',
 
'method'=>'flickr.photos.search',
 
'tags'=>'Radiohead',
 
'per_page'=>'30'
 
);
 
 
 
  //  Send request and read response
 
$result = $client->call('FlickrRequest', $request, "urn:flickr");
 
  $data = html_entity_decode($client->responseData);
 
 
 
  // get rid of name spaces
 
  $data = str_replace("s:", "", $data);
 
  $data = str_replace("x:", "", $data);
 
 
 
  // Convert xml to object
 
  $xml = simplexml_load_string($data);
 
 
 
  foreach($xml->Body->FlickrResponse->photos->photo as $one_photo)
 
  {
 
    $url = "http://farm{$one_photo['farm']}.static.flickr.com/{$one_photo['server']}/{$one_photo['id']}_{$one_photo['secret']}.jpg";
 
    $title = $one_photo['title'];
 
   
 
    //print "<h2>{$title}<h2>";
 
    print "<img src=\"{$url}\" title=\"$title\" style=\"height: 100px; padding: 2px\">";
 
  }
 
?>
 
 
</pre>
 
</pre>
 +
Please note:
 +
* We are using XML in this example, but you could try using JSON.
 +
* Once we have the XML data, but simply pass it on to a new view (see below).
  
All done! Your page should look like this:
+
=== The view ===
* [https://mi-linux.wlv.ac.uk/~in9352/apis/flickr-soap.php https://mi-linux.wlv.ac.uk/~in9352/apis/flickr-soap.php]
 
 
 
== OAuth authentication example ==
 
 
 
More and more APIs require your to authenticate and sign your request using the [https://oauth.net/ OAuth protocol].
 
 
 
In this example we will access the Yelp API to list local pubs, with address and rating. Here's the documentation for the API:
 
* [https://www.yelp.com/developers/documentation/v2/search_api https://www.yelp.com/developers/documentation/v2/search_api]
 
 
 
It uses the OAuth.php library that can be downloaded from here:
 
* [https://github.com/Yelp/yelp-api/tree/master/v2/php/lib https://github.com/Yelp/yelp-api/tree/master/v2/php/lib]
 
 
 
The source code is quite involved, but each line is commented, so please study the listing carefully:
 
  
 +
Next, create a new view (Views/apis/wikipedia.php):
 
<pre>
 
<pre>
<?php
+
<?php foreach($links->query->exturlusage->eu as $link):?>
 
+
    <h2><?=$link['title']?></h2>
// Based on https://github.com/Yelp/yelp-api/tree/master/v2/php
+
    <p>Links to: <a href='<?=$link['url']?>'><?=$link['url']?></a></p>
 
+
    <p>pageid: <?=$link['pageid']?></p>
// Enter the path that the oauth library is in relation to the php file
+
<?php endforeach?>  
require_once('lib/OAuth.php');
 
 
 
// Set your OAuth credentials here 
 
// These credentials can be obtained from the 'Manage API Access' page in the
 
// developers documentation (http://www.yelp.com/developers)
 
$CONSUMER_KEY = "GET YOUR OWN!!!";
 
$CONSUMER_SECRET = "GET YOUR OWN!!!";
 
$TOKEN = "GET YOUR OWN!!!";
 
$TOKEN_SECRET = "GET YOUR OWN!!!";
 
 
 
// Build URL for our request
 
$unsigned_url = "https://api.yelp.com/v2/search?";
 
$unsigned_url.= "term=pubs&";
 
$unsigned_url.= "location=Wolverhampton";
 
print $unsigned_url."<br>";
 
 
 
// Token object built using the OAuth library
 
$token = new OAuthToken($GLOBALS['TOKEN'], $GLOBALS['TOKEN_SECRET']);
 
 
 
// Consumer object built using the OAuth library
 
$consumer = new OAuthConsumer($GLOBALS['CONSUMER_KEY'], $GLOBALS['CONSUMER_SECRET']);
 
 
 
// Yelp uses HMAC SHA1 encoding
 
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();
 
 
 
$oauthrequest = OAuthRequest::from_consumer_and_token(
 
$consumer,
 
$token,
 
'GET',
 
$unsigned_url
 
);
 
 
 
// Sign the request
 
$oauthrequest->sign_request($signature_method, $consumer, $token);
 
 
 
// Get the signed URL
 
$signed_url = $oauthrequest->to_url();
 
 
 
// Send Yelp API Call
 
$ch = curl_init($signed_url);
 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
curl_setopt($ch, CURLOPT_HEADER, 0);
 
$data = curl_exec($ch);
 
 
 
// Convert JSON string to PHP object
 
$dataArray = json_decode($data);
 
 
 
// Loop through object and display
 
foreach($dataArray->businesses as $business) {
 
echo "<h2>{$business->name}</h2>";
 
echo "<p>Address: {$business->location->display_address[0]}</p>";
 
echo "<p>Phone: {$business->phone}</p>";
 
echo "<p>Rating: {$business->rating}/5</p>";
 
}
 
 
 
?>
 
 
</pre>
 
</pre>
 
+
Please note:
Working example here: [https://mi-linux.wlv.ac.uk/~in9352/apis/yelp.php https://mi-linux.wlv.ac.uk/~in9352/apis/yelp.php]
+
* It's a simple foreach loop, that displays all items.
 +
* Here is my working example: [https://mi-linux.wlv.ac.uk/~in9352/ci4/public/apis/wikipedia https://mi-linux.wlv.ac.uk/~in9352/ci4/public/apis/wikipedia]

Revision as of 17:19, 21 January 2022

Main Page >> Advanced Web Development >> Workbook >> Week 05

REST - The Wikipedia API

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! (look at the address bar)

Note that we are passing the following parameters:

  • action = query
  • list = exturlusage (the service we are requesting)
  • format = xml (the format of the response)
  • euquery = www.bdtheque.com (the parameter required for this service)

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

The controller

Create a 'new Apis.php controller:

<?php

namespace App\Controllers;

use App\Models\NewsModel;

class Apis extends BaseController
{
	public function wikipedia()
	{
		// Since 2010 a user agent is required
		ini_set('user_agent', 'University of Wolverhampton');

		$website = "www.bdtheque.com";

		$url = "http://en.wikipedia.org/w/api.php?"
			."action=query&"
			."list=exturlusage&"
			."eulimit=500&"
			."format=xml&"
			."euquery=".$website;
		  
		// Get data from URL and store in object
		$data['links'] = simplexml_load_file($url);
		$data['title'] = "Wikipedia API";

		echo view('templates/header', $data);
		echo view('apis/wikipedia', $data);
		echo view('templates/footer', $data);		
	}
}

Please note:

  • We are using XML in this example, but you could try using JSON.
  • Once we have the XML data, but simply pass it on to a new view (see below).

The view

Next, create a new view (Views/apis/wikipedia.php):

<?php foreach($links->query->exturlusage->eu as $link):?>
    <h2><?=$link['title']?></h2>
    <p>Links to: <a href='<?=$link['url']?>'><?=$link['url']?></a></p>
    <p>pageid: <?=$link['pageid']?></p>
<?php endforeach?> 

Please note: