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

From mi-linux
Jump to navigationJump to search
 
(47 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Main Page]] >> [[CP3207|Web Application Development]] >> [[Web Application Developpment - Workbook|Workbook]] >> Week 07
+
[[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 known REST example and a known SOAP example:
+
'''Important''': this is a CodeIgniter example, but it is easily adaptable to Laravel.
  
* REST - The Amazon API
+
== REST - The Wikipedia API ==
* SOAP - The Google Search API
 
  
== A REST example: Amazon ==
+
Let’s simply find all all the Wikipedia pages that link to my website [http://www.bdtheque.com www.bdtheque.com] :o)
  
Note that Amazon is one of the rare providers to still offer both REST and SOAP interfaces to their services… let’s have a look at their REST API.
+
With REST, it's all about calling the right URL, passing in the right parameters... here is the URL we need:
  
First, let’s simply select the top selling books on Amazon.com
+
[http://en.wikipedia.org/w/api.php?action=query&list=exturlusage&format=xml&euquery=www.bdtheque.com Click me!] (look at the address bar)
  
With REST, it's all about calling the right URL, passing in the right parameters... here is the URL for the top selling books on Amazon.com:
+
Note that we are passing the following parameters:
 
+
* action = query
[http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&SubscriptionId=0NR4EHP6HAVW61V6P1G2&Operation=BrowseNodeLookup&BrowseNodeId=283155&ResponseGroup=TopSellers Click me!]
+
* 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).
 
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!
+
=== The controller ===
  
 +
Create a new '''Apis.php''' controller:
 
<pre>
 
<pre>
<H1>Top Selling Books on Amazon.com at <?= date("d-m-Y H:i"); ?></H1>
+
<?php
<?
 
 
  // My key is 0NR4EHP6HAVW61V6P1G2
 
  // APPLY FOR YOUR OWN KEY!!
 
 
  // Node for books
 
  $node = 283155;
 
 
  // Build REST url
 
  $url = "http://webservices.amazon.com/onca/xml?";
 
  $url.= "Service=AWSECommerceService&";
 
  $url.= "SubscriptionId=0NR4EHP6HAVW61V6P1G2&";
 
  $url.= "Operation=BrowseNodeLookup&";
 
  $url.= "BrowseNodeId=$node&";
 
  $url.= "ResponseGroup=TopSellers";
 
  
  // Get raw data
+
namespace App\Controllers;
  $response = file_get_contents($url);
 
 
 
  // 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>";
 
  }
 
  
?>
+
use App\Models\NewsModel;
</pre>
+
 
 +
class Apis extends BaseController
 +
{
 +
public function wikipedia()
 +
{
 +
// Since 2010 a user agent is required
 +
ini_set('user_agent', 'University of Wolverhampton');
  
And that’s it! Your page should now be displaying the titles of the top selling books.
+
$website = "www.bdtheque.com";
  
But what if you want to know more about those books? Well you need to send another request to ask for more details on each book… The following example builds on the previous one, and displays a picture of the book cover next to its title! You could display a lot more (authors, similar books, prices etc…) but we’ll leave that bit up to you.
+
$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";
  
<pre>
+
echo view('templates/header', $data);
<H1>Top Selling Books on Amazon.com at <?= date("d-m-Y H:i"); ?></H1>
+
echo view('apis/wikipedia', $data);
<?
+
echo view('templates/footer', $data);
+
}
  // My key is 0NR4EHP6HAVW61V6P1G2
+
}
  // APPLY FOR YOUR OWN KEY!!
 
 
  // Node for books
 
  $node = 283155;
 
 
  // Build REST url
 
  $url = "http://webservices.amazon.com/onca/xml?";
 
  $url.= "Service=AWSECommerceService&";
 
  $url.= "SubscriptionId=0NR4EHP6HAVW61V6P1G2&";
 
  $url.= "Operation=BrowseNodeLookup&";
 
  $url.= "BrowseNodeId=$node&";
 
  $url.= "ResponseGroup=TopSellers";
 
       
 
  // Get raw data
 
  $response = file_get_contents($url);
 
 
 
  // Convert raw data to object
 
  $xml = simplexml_load_string($response);
 
 
  // Put a;; asin numbers into a variable
 
  $ASIN = "";
 
  foreach($xml->BrowseNodes->BrowseNode->TopSellers->TopSeller as $book)
 
  {
 
    $ASIN = $ASIN.$book->ASIN.",";
 
  }
 
 
  // Make second call, asking for more details
 
 
 
  $url = "http://webservices.amazon.com/onca/xml?";
 
  $url.= "Service=AWSECommerceService&";
 
  $url.= "SubscriptionId=0NR4EHP6HAVW61V6P1G2&";
 
  $url.= "Operation=ItemLookup&";
 
  $url.= "ItemId=$ASIN&";
 
  $url.= "ResponseGroup=Medium";
 
 
 
  $response = file_get_contents($url);
 
  $xml = simplexml_load_string($response);
 
 
  foreach($xml->Items->Item as $bd)
 
  {
 
    $ASIN = $bd->ASIN;
 
    $image = $bd->MediumImage->URL;
 
    $url = $bd->DetailPageURL;
 
    $Title =$bd->ItemAttributes->Title;
 
 
    echo "<IMG src=\"$image\">";
 
    echo "$Title<BR>";
 
   
 
  }
 
?>
 
 
</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).
  
== A SOAP example: Google Search ==
+
=== The view ===
  
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.
+
Next, create a new view (Views/apis/wikipedia.php):
 +
<pre>
 +
<?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?>
 +
</pre>
 +
Please note:
 +
* 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]
  
* [http://sourceforge.net/projects/nusoap/files/ http://sourceforge.net/projects/nusoap/files/]
+
== REST - Authentication via CURL ==
  
Simply unzip the archive in your web pages’ folder.
+
Some APIs will ask you to authenticate, by providing specific HTTP headers. This can be achieved using the [https://www.php.net/manual/en/intro.curl.php cURL PHP library], which "allows you to connect and communicate to many different types of servers with many different types of protocols."
  
Now the code… well nothing too difficult here.  
+
=== Reed.co.uk example ===
* First you include the library you have just downloaded
+
The Reed API located [https://www.reed.co.uk/developers/jobseeker here] explains that "You will need to include your api key for all requests in a basic authentication http header as the username, leaving the password empty."
* Then you create a SOPA 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.
 
  
 +
You can achieve this in PHP like this:
 
<pre>
 
<pre>
<?
+
<?php
  require("nusoap/lib/nusoap.php");
 
  
  // What we are searching for
+
// Set connection details
  $search = "Alix Bergeret";
+
$login = 'PUT YOUR REED API KEY HERE';
 +
$password = '';
 +
$url = 'https://www.reed.co.uk/api/1.0/search?keywords=laravel&location=wolverhampton&distancefromlocation=15';
  
  // Create soap client
+
// Create CURL object with options
  $client = new soapclient("http://api.google.com/GoogleSearch.wsdl", true);
+
$ch = curl_init();
 +
curl_setopt($ch, CURLOPT_URL,$url);
 +
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
 +
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 +
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
  
  // Set encoding
+
// Make CURL call, and convert result to JSON object
  $client->soap_defencoding = 'UTF-8';
+
$jobs = curl_exec($ch);
 +
$jobs = json_decode($jobs);
 +
curl_close($ch);
  
  // Prepare request
+
// Display results
  $request = array(
+
foreach($jobs->results as $job) {
'key'=>'4B0KufpQFHJxhAxzua0tR11ElLNrHRJ6',
+
print($job->jobTitle . "<br>");
'q'=>$search,
+
}
'start'=>0,
+
</pre>
'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
+
Here is my working example
  foreach($result['resultElements'] as $one_result)
+
* [https://mi-linux.wlv.ac.uk/~in9352/apis/reed.php https://mi-linux.wlv.ac.uk/~in9352/apis/reed.php]
  {
 
    print "<h1>{$one_result['title']}</h1>";
 
    print "<p>{$one_result['snippet']}</p>";
 
  }
 
?>
 
</pre>
 
  
All done!
+
== Going further: the OpenWeatherMap API ==
 +
Adapt the example above to obtain current weather data for Wolverhampton, from the OpenWeatherMap API:
 +
* [https://openweathermap.org/current https://openweathermap.org/current]
 +
* You'll need to register for a free API Key
 +
* Like the Wikipedia API, the OpenWeatherMap API supports both XML and JSON.

Latest revision as of 14:31, 21 February 2023

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

Important: this is a CodeIgniter example, but it is easily adaptable to Laravel.

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:

REST - Authentication via CURL

Some APIs will ask you to authenticate, by providing specific HTTP headers. This can be achieved using the cURL PHP library, which "allows you to connect and communicate to many different types of servers with many different types of protocols."

Reed.co.uk example

The Reed API located here explains that "You will need to include your api key for all requests in a basic authentication http header as the username, leaving the password empty."

You can achieve this in PHP like this:

<?php

// Set connection details
$login = 'PUT YOUR REED API KEY HERE';
$password = '';
$url = 'https://www.reed.co.uk/api/1.0/search?keywords=laravel&location=wolverhampton&distancefromlocation=15';

// Create CURL object with options
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");

// Make CURL call, and convert result to JSON object
$jobs = curl_exec($ch);
$jobs = json_decode($jobs);
curl_close($ch);  

// Display results
foreach($jobs->results as $job) {
	print($job->jobTitle . "<br>");
}

Here is my working example

Going further: the OpenWeatherMap API

Adapt the example above to obtain current weather data for Wolverhampton, from the OpenWeatherMap API: