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

From mi-linux
Jump to navigationJump to search
Line 19: Line 19:
 
=== The controller ===
 
=== The controller ===
  
Create a '''new Apis.php'' controller:
+
Create a '''new Apis.php''' controller:
 
<pre>
 
<pre>
 
<?php
 
<?php

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: