Chapter 3. REST in the Real World

There is a wide use of REST style services today. Many web applications provide REST style interfaces so that the developers can implement value added applications using the REST interfaces of those web applications.

In this chapter, we are going to use some of those publicly available REST style services and build our own value added content. Some of the services that we will be using are:

  • BBC news feeds

  • Yahoo news search

  • Yahoo maps

  • Yahoo local search

  • Earthquakes feed

Types of Services Available

The REST style services available today have many forms. Some have custom APIs defined, where we can find API documents defining the input, output formats, and the resource URI information. Examples are the Flickr API, Amazon API, and Yahoo REST API.

There are various XML feeds such as RSS feeds and Atom Feeds available around the Web today. As an example, news websites and Weblogs (better known as Blogs) use either RSS or Atom feeds to reflect the latest updates. Since they also deal with information we can also consider those as a form of REST style services. Feeds provide users with frequently updated content and hence are often used for distributing news. There are two main feed formats, RSS (http://en.wikipedia.org/wiki/RSS_(file_format)) and ATOM (http://en.wikipedia.org/wiki/Atom_(standard)). All major news sites as well as blogs have associated feeds in both formats.

Some of the REST style services can also deliver formats other than XML. The simplest example is the use of images while using a map related applications such as Google Maps or Yahoo Maps. The JSON (http://www.json.org/) standard is also popular. PHP allows for different input/output formats to be dealt with flexibly. One of the advantages of REST is its diversity and adaptability to make use of the flexibility that PHP provides. However, the basic REST principles do not change irrespective of the opportunity to use various message formats.

Consuming Real-World Services

In this section, we will explore how to consume REST services and build value added applications on top of those services.

Before consuming a service, understanding the service involves several steps:

  • Find out what the input parameters and format of those parameters are and prepare the input

  • Find out the service endpoint that is the URL, and the HTTP verb expected. Some services also expect particular content type information

  • Find out the response format and explore how to process the expected response to pick the information required out of the response

  • Check the terms of use of the service:

    • API rate limits Depending on API rate limits, that is how much does it cost to invoke a single operation using the API, our approach might differ with intermediate proxying or other variants of preserving/caching results of API calls.

    • Copyright implications Some of the content that you receive as a result of an API call might be copyrighted. You have to be sensitive to copyright implications before using that content in your web application.

    • Service level commitments While using a publicly available service, there could be situations that the service provider is strained due to too many people accessing the service concurrently. So the service provider would define some service level constraints in terms of quality of the service. As an example, if you have performance commitments in your web application, then you have to be sensitive to response time commitments from the service. If you want to display the results from the service on your web application within an acceptable time period, where your web application's users would not feel it to be too slow, you may have to be sensitive to response time service level constraints defined by the service provider.

    • Service level commitments While using a publicly available service, there could be situations that the service provider is strained due to too many people accessing the service concurrently. So the service provider would define some service level constraints in terms of quality of the service. As an example, if you have performance commitments in your web application, then you have to be sensitive to response time commitments from the service. If you want to display the results from the service on your web application within an acceptable time period, where your web application's users would not feel it to be too slow, you may have to be sensitive to response time service level constraints defined by the service provider.

Note that most API documents explicitly mention if a given input parameter is mandatory or optional. You must pay attention to those details to ensure that all mandatory parameters are present in a request. Similarly, the output from the service could also have mandatory as well as optional parts. While you can assume the mandatory parts to be present, your response processing logic must have provisions to deal with optional parts, or else your application may fail.

Interpreting APIs could get complicated based on the way the API is designed. While using REST services designed and deployed by others, we often have no control over the way it is designed and we cannot afford to change it ourselves. Hence the chances are that we need to learn how to live with those public REST service APIs that we want to use.

If you have difficulties understanding the service API documents, try to send a request to the service, capture the response and print it out. Most API documents provide dummy request/response as templates. You can use those to help you build the request for your initial tests. If the API documents do not provide those, you could try to create dummy request/responses templates based on whatever information is provided in the API documentation. These steps help you build confidence on the service API in the prototyping phase. Also note that most services often provide us with a sandbox to help developers play around with the API and get familiar with the API.

During the prototyping phase, the chances are that you will run into errors. Pay attention to the error information returned in the error messages. Often, the error information could lead you to clues as to how you could solve the problems.

Once you have some basic understanding and get your first few requests to work then you can read the API document carefully to find more details.

It should also be mentioned that service APIs often change because the services evolve over time and your client code should be able to deal with the changing mandatory/required fields. Thus, creating abstraction layers is always a good idea to deal with the API changes. Also, while interpreting APIs, it's good to never rely on personal findings. Sometimes, looking at a particular response to a request, you may come up with some assumptions on the format for the response. Make sure you try several different request scenarios with several different valid and invalid values for input parameters before you make such assumptions. Make things as robust as possible so that your XML parser can deal with position-changes of XML elements and maybe not even use XML strict parsing.

Cresting our Utility Code—RESTUtil.php

Let's define some utility functions that we are going to use for the samples throughout this chapter.

This would help us to modularize our client PHP scripts and make sure that we re-use the utility functions. It will lead us to focus more on the business logic while implementing client scripts without having to worry about the repetitive tasks such as building the query strings and forming the CURL options for HTTP GET requests. Please note that we can use REST services without this utility script, but this script would help us to be more organized while implementing client scripts.

We will name this script RESTUtil.php.

<?php
function build_query_string(array $params) {
$query_string = http_build_query($params);
return $query_string;
}
function curl_get($url) {
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($client);
curl_close($client);
return $response;
}
?>

The build_query_string function builds the HTTP query string for a given request parameter array.

The curl_get function would execute a GET request on the given URL and return the response. Note that this function assumes that the given URL would include the query parameters, if any, required by the service.

Consuming an RSS Feed&mdash;BBC News Feed

The BBC provides a number of news feeds on various categories of news. You can find the feed URLs at http://news.bbc.co.uk/2/hi/help/3223484.stm.

Consuming an RSS Feed&mdash;BBC News Feed

In the next PHP script we will access the technology news feed.

<?php
require_once 'RESTUtil.php';
$url = 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/technology/rss.xml';
$response = curl_get($url);
$xml = simplexml_load_string($response);
foreach ($xml->channel->item as $item) {
echo $item->title . "
";
}
?>

First of all, note that we include the RESTUtil.php with utility functions at the top of the source code. The output generated when the PHP script is run is shown below:

Consuming an RSS Feed&mdash;BBC News Feed

The response from the feed would be in RSS version 2.0 format. You can find more information on RSS formats form http://www.rssboard.org/rss-history. The following XML snippet shows the format of the response received. Note that the following XML is what you receive from the service located at http://newsrss.bbc.co.uk/rss/newsonline_world_edition/technology/rss.xml. The client PHP script that was shown above process this XML response in order to prepare its output, which is shown above.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<?xml-stylesheet title="XSL_formatting" type="text/xsl" href="/shared/bsp/xsl/rss/nolsol.xsl"?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss">
<channel>
<item>
<title>Future web</title>
<description>
Luminaries predict the shape of tomorrow's world wide
web
</description>
<link>
http://news.bbc.co.uk/go/rss/ -/2/hi/technology/7373717.stm
</link>
<guid isPermaLink="false">
http://news.bbc.co.uk/1/hi/technology/7373717.stm
</guid>
<pubDate>Wed, 30 Apr 2008 09:32:41 GMT</pubDate>
<category>Technology</category>
</item>
<item>
<title>The offline cost of an online life</title>
<description>
Bill Thompson wonders if his virtual presences are
having a significant real world impact.
</description>
<link>
http://news.bbc.co.uk/go/rss/ -/2/hi/technology/7300403.stm
</link>
<guid isPermaLink="false">
http://news.bbc.co.uk/1/hi/technology/7300403.stm
</guid>
<pubDate>Tue, 18 Mar 2008 08:53:18 GMT</pubDate>
<category>Technology</category>
</item>
</channel>
</rss>

There are multiple item elements in the response representing Technology news elements. In the PHP source code from the XML tree, we print out the title of each news item. Based on the requirements of your program, you can choose to pick any of the other sub-elements from each item element. As an example, if you want the news link you could have used:

echo $item->link . "
";

Printing out the feed is very straightforward. Let's see how to combine the information from the feed with another Service.

BBC News Feed with Yahoo News Search

In this example, we would pick the titles from the BBC news feed and search for the related news items for Yahoo news search.

<?php
require_once 'RESTUtil.php';
$url = 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/technology/ rss.xml';
$response = curl_get($url);
$xml = simplexml_load_string($response);
$base_url = 'http://search.yahooapis.com/NewsSearchService/V1/newsSearch';
foreach ($xml->channel->item as $item) {
echo '<h2>' . $item->title . '</h2>'. "
";
$params = array (
REST servicesYahoo news search, using'appid' => 'YahooDemo',
'query' => $item->title,
'results' => 2,
'language' => 'en'
);
$url = "$base_url?" . build_query_string($params);
$response = curl_get($url);
$xml = simplexml_load_string($response);
echo '<ul>' ."
";
foreach ($xml->Result as $news) {
echo '<li><a href='' . $news->Url . ''/>' . $news->Title . '</a></li>' . "
";
}
echo '</ul>' ."
";
}
?>

This source code is self-descriptive.

Here is the logical breakdown of the script:

  • Fetch the news feed.

  • First we define the feed URL.

$url = 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/ technology/rss.xml';
  • Then we get the feed content using CURL and capture the response.

$response = curl_get($url);
  • Next we build the SimpleXML object structure using the received response.

$xml = simplexml_load_string($response);
  • For each news title, search Yahoo for related news.

  • Using the XML object structure that we build based on the response, we can find out the news title of each news item.

foreach ($xml->channel->item as $item) {
echo '<h2>' . $item->title . '</h2>'. "
";

Then for each news item title, while staying in the for loop, we prepare the array of parameters to be used with Yahoo search query.

$params = array (
'appid' => 'YahooDemo',
'query' => $item->title,
'results' => 2,
'language' => 'en'
);
  • Note that we are going to search for the news item's title, and we are looking for two search results, as well as our language preference is English.

  • And next, we build the query string using the array of parameters.

$url = "$base_url?" . build_query_string($params);
  • Note that our base URL is:

$base_url = 'http://search.yahooapis.com/NewsSearchService/V1/ newsSearch';
  • This is the URL where Yahoo News Search is located.

  • Next, we send a GET request to the URL using CURL, capture the response, and build a SimpleXML object structure using the response.

$response = curl_get($url);
$xml = simplexml_load_string($response);
  • Now we are ready to use the news results from Yahoo and display them in a useful format.

  • Print out the result picking the required data elements and formatting them to suit the desired output.

  • For each news result item in the XML structure that we built using the response, we pick the news URL and link that with the news title.

foreach ($xml->Result as $news) {
echo '<li><a href='' . $news->Url . ''/>' . $news->Title . '</a></li>' . "
";
  • Here is a fragment of the output from this program.

<h2>The offline cost of an online life</h2>
Yahoo news search, REST serviceslogical script breakdown<ul>
<li><a href='http://www.ecommercetimes.com/rsstory/62852.html'/>eBay, Craigslist Soap Opera Unfolds</a></li>
<li><a href='http://www.onrec.com/newsstories/21420.asp'/>Issue 102 - 5th April - 1st May</a></li>
</ul>
<h2>Future web</h2>
<ul>
<li><a href='http://www.cnn.com/2008/SHOWBIZ/TV/05/01/tv.future/index.html?section=cnn_latest'/>Is the future of TV on the Web?</a></li>
<li><a href='http://news.bbc.co.uk/go/rss/-/1/hi/technology/7373717.stm'/>Luminaries look to the future web</a></li>
</ul>

The output looks very interesting:

BBC News Feed with Yahoo News Search

Yahoo Maps and Local Search

Yahoo maps and Google Maps are popular map serving applications on today's Internet. Both these applications provide us with REST APIs, so we can build interesting map related applications.

In this section, we will see how to combine the results of a local search and show the results on a map. Yahoo provides an AJAX based API to fetch a map and display it on a web browser. The API documentation is found at http://developer.yahoo.com/maps/ajax/index.html. Yahoo also provides a local search API, using which one can search for businesses near a specified location. The API for this service can be found at http://developer.yahoo.com/search/local/V3/localSearch.html. In the next PHP sample source code, we will use the local API to search hotels near Cambridge, MA area, and display them on a map.

Please note that in order to use the Yahoo! maps services, you need to get an application developer ID by registering at https://developer.yahoo.com/wsregapp/.

In the following sample, we are using a mix of JavaScript and PHP. One could have done all the processing with AJAX and not use PHP at all. One of the advantages of using PHP is that it is a feature rich language compared to JavaScript. Hence, if you have to do some complex processing, you would be better-off doing them with PHP on server side before pushing the results to the web browser. Note that AJAX processing happens within the web browser on the user machine, whereas PHP processing happens on server side.

If everything is done in PHP, there is a chance that the user would notice a delay in response because all processing happens before anything is sent to be displayed on the web browser. If everything is done on the web browser using AJAX, the user experience again can be affected by the resources available on the user machine. So there needs to be a correct mix of JavaScript and PHP used, and the correct mix needs to be figured out through experimenting based on the kind of application that you are building.

One of the other key aspects that must be kept in mind while using AJAX is the Web browser compatibility issues. Different Web browsers like Firefox and Internet Explorer can behave differently for the same piece of JavaScript code. If you stick to PHP and HTML alone, these could be avoided, however, JavaScript comes in handy when developing web applications with rich user experience.

<?php
REST servicessource coderequire_once 'RESTUtil.php';
function location_search($query, $in_location) {
$base_url = 'http://local.yahooapis.com/LocalSearchService/V3/localSearch';
$params = array (
'appid' => 'YahooDemo',
'query' => $query,
'location' => $in_location
);
$url = $base_url . "?" . build_query_string($params);
$response = curl_get($url);
$xml = simplexml_load_string($response);
foreach ($xml->Result as $location) {
$data = array((string)$location->Latitude, (string)$location->Longitude,
(string)$location->Title);
$output[] = $data;
}
return $output;
}
function write_map_script(array $points) {
// center map on the middle result and draw
if (count($points) > 0) {
$middle_point = $points[count($points) / 2];
$js_middle = <<<JAVA_SCRIPT
var points = new YGeoPoint($middle_point[0], $middle_point[1]);
map.drawZoomAndCenter(points, 5);
JAVA_SCRIPT;
foreach ($points as $id => $obj) {
$map_point_name = addslashes($obj[2]);
$js_end = <<<JAVA_SCRIPT
var point$id =
new YGeoPoint($obj[0],$obj[1]);
var current_marker = new YMarker(point$id);
current_marker.addLabel('$id'),
current_marker.addAutoExpand('<div class="mp">$map_point_name</div>');
map.addOverlay(current_marker);
JAVA_SCRIPT;
$js_middle .= $js_end;
REST servicessource code}
}
echo $js_middle . $js_end;
}
$points = location_search('Hotel', 'Cambridge, MA');
?>
<html>
<head>
<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=1d023cfa8f244bbacc42b7d67658ba3d">
</script>
<style>
#mapHolder {
height: 700px;
width: 700px;
}
</style>
</head>
<body>
<div id="mapHolder"></div>
<script type="text/javascript">
var map = new YMap(document.getElementById('mapHolder'), YAHOO_MAP_REG);
map.addZoomShort();
map.addPanControl();
<?php write_map_script($points); ?>
</script>
</body>
</html>

Though this source code is a bit lengthier, we can easily break this down into several logical sections.

  • Function implementations

  • Calling functions to do the search and update the map

  • HTML display

We have two functions in this source code. One is location_search() and the other is write_map_script().

function location_search($query, $in_location) {

The location_search() function does search for given businesses in a given location. The first parameter to this function indicates the kind of business to search for and the second parameter indicates the area to search. In this example, the value of the first parameter is Hotel and the second parameter is Cambridge, MA , because we want to search for hotels around the Cambridge area.

The code within the location_search() function should be very familiar to you by now. We build the URL using the base URL and the query parameters string.

$base_url = 'http://local.yahooapis.com/LocalSearchService/V3/localSearch';
$params = array (
'appid' => 'YahooDemo',
'query' => $query,
'location' => $in_location
);
$url = $base_url . "?" . build_query_string($params);

Send the request using CURL API.

$response = curl_get($url);

Receive the response and process the response XML to pick the information we want.

$xml = simplexml_load_string($response);
foreach ($xml->Result as $location) {
$data = array((string)$location->Latitude, (string)$location->Longitude,
(string)$location->Title);
$output[] = $data;
}

In this case, for each search result item, we are picking up the latitude, longitude and the title. Latitude and longitude are required to mark the point on the map and the title would be used to display the tip when the user moves the mouse over the marked point on the map.

The second function is write_map_script() and is used to build the JavaScript required to mark the points on the map with the search results. We use the YMap and YGeoPoint classes from the Yahoo AJAX map API.

To understand the flow of this source code, you have to start reading the code from the line:

$points = location_search('Hotel', 'Cambridge, MA'),

This line is the entry point to the code, from here you can move to location_search() function and follow the code located there and come back to the above line and follow the code down to the HTML section.

Note that, while using PHP and JavaScript, you may come up with situations where you have to interchange data between PHP and JavaScript. Passing values of PHP variables to JavaScript is demonstrated in the following sample. You can use a PHP string and build the JavaScript code and at the same time use PHP variables.

$js_middle = <<<JAVA_SCRIPT
var points = new YGeoPoint($middle_point[0], $middle_point[1]);
map.drawZoomAndCenter(points, 5);
JAVA_SCRIPT;

The other interesting question is if we can pass variable values in JavaScript to PHP. One way of accomplishing this is to generate JavaScript code with PHP, and have the browser refresh itself, passing specific variables back to the PHP script. See http://php.net/manual/en/faq.html.php#faq.html.javascript-variable for more details. Another option is to use XMLHttpRequest (http://www.w3.org/TR/XMLHttpRequest/) and make a call to the PHP script.

In the HTML section, we first import the Yahoo AJAX map script:

<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=your_api_key">
</script>

Note that you must replace your_api_key with your Yahoo API key for this sample to work for you.

Within the HTML section we have a PHP code snippet where we call the write_map_script() with the points array returned by the location_search() function. And the write_map_script() would do what is necessary to mark the points on the map corresponding to the search results.

Here is the output from this script.

Yahoo Maps and Local Search

One of the interesting things to note with Yahoo local search API is that it is capable of giving you the output in both JSON as well as PHP serialized format in addition to the XML format that we used in the above example. In case you want to use the PHP serialization format for output, you need to set the output parameter to the value php , and need to use the unserialize function (http://www.php.net/manual/en/function.unserialize.php) to convert the received response to a PHP array.

Here is the same example, with PHP output format used for local search.

<?php
require_once 'RESTUtil.php';
function location_search($query, $in_location) {
$base_url = 'http://local.yahooapis.com/LocalSearchService/V3/localSearch';
$params = array (
'appid' => 'YahooDemo',
'output' => 'php',
'query' => $query,
'location' => $in_location
);
$url = $base_url . "?" . build_query_string($params);
$response = curl_get($url);
$output = unserialize($response);
return $output['ResultSet']['Result'];
}
function write_map_script(array $points) {
// center map on the middle result and draw
if (count($points) > 0) {
$middle_point = $points[count($points) / 2];
$js_middle = <<<JAVA_SCRIPT
var points = new YGeoPoint($middle_point[0], $middle_point[1]);
map.drawZoomAndCenter(points, 5);
JAVA_SCRIPT;
foreach ($points as $id => $obj) {
$map_point_name = addslashes($obj[2]);
$js_end = <<<JAVA_SCRIPT
var point$id =
 new YGeoPoint($obj[0],$obj[1]);
var current_marker = new YMarker(point$id);
current_marker.addLabel('$id'),
current_marker.addAutoExpand(
'<div class="mp">$map_point_name</div>');
map.addOverlay(current_marker);
JAVA_SCRIPT;
$js_middle .= $js_end;
}
}
echo $js_middle . $js_end;
}
$results = location_search('Hotel', ' Cambridge, MA');
foreach ($results as $id => $data) {
$points[$id] = array (
$data['Latitude'],
 $data['Longitude'],
 $data['Title']
);
}
?>
<html>
<head>
<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=your_api_key">
</script>
<style>
#mapHolder {
height: 700px;
width: 700px;
}
REST servicesPHP output format</style>
</head>
<body>
<div id="mapHolder"></div>
<script type="text/javascript">
var map = new YMap(document.getElementById('mapHolder'), YAHOO_MAP_REG);
map.addZoomShort();
map.addPanControl();
<?php write_map_script($points); ?>
</script>
</body>
</html>

Note that, not only has the location_search() function been slightly changed, but the way that the return value from that function is being processed. In the previous version of this sample we picked the XML elements that we wanted and prepared the points array. However, in this sample, we are processing the array returned as a serialized PHP object and we pick the array elements that we want from that array and build the points array. While using the XML format, the application is easier to debug because the messages passed back and forth between the service and our script would be human readable. However, while using the serialized PHP format, it would be harder to debug the script as the messages sent are in binary format and are not readable.

The advantage of using binary serialized PHP format is that it is more efficient compared to the XML format. On one hand, the serialized PHP format would be compact compared to the XML message format. Apart from the real valuable content, an XML message needs XML element name tags to mark the boundaries between element contents and that makes the XML message bulky. The other fact to note is that, while using XML format, there needs to be some XML processing to extract the required data form the incoming XML message. However, while using serialized PHP objects, we just need to call the unserialize() method. This is far more efficient than parsing and processing the XML message.

Earthquakes and Yahoo Maps

In the previous sample we used a Yahoo service that gave us latitude and longitude directly. However, there could be situations where we have to find or compute those values. http://www.ga.gov.au/rss/quakesfeed.rss gives an RSS feed of the earthquakes that have taken place. The longitude and latitude information is embedded in the description tag within item.

<item>
<title>04/05/2008 22:14:32(UTC) North East of Northam, WA (Preliminary)</title>
<link>http://www.ga.gov.au/bin/earthquake.pl?title=North+East+of+Northam%2C+WA+%28Preliminary%29&amp;magnitude=3.8&amp;depth=0&amp;xy=117.580,-31.127&amp;date=04,05,2008&amp;time=22,14,32&amp;bg1=eqrisk_lm&amp;zoom=100&amp;station=MORW"</link>
<description> Latitude: -31.127 Longitude: 117.58 Magnitude: 3.8 Depth(km): 0</description>
</item>

We can pick the latitude and longitude information from the description tag's text using the split() operation. Then we can use logic similar to the Yahoo local search program. However, it is simpler to extract the longitude and latitude information using xy parameter in the link tag.

First we can locate the link element using the code snippet:

$item->link

This string would have the form:

To mark the map, we need to pick the latitude and longitude from this string. In the xy parameter, x maps to longitude and y maps to latitude.

We can use parse_str function to split the string and pick the xy parameter.

parse_str($item->link, $params);

Then we can split the xy parameter to pick the coordinates that map to the longitude and the latitude.

$coords = split(",", $params['xy']);

Here is the complete code for this example:

<?php
require_once 'RESTUtil.php;
function get_quakes() {
$url = 'http://www.ga.gov.au/rss/quakesfeed.rss';
$response = curl_get($url);
$xml = simplexml_load_string($response);
foreach ($xml->channel->item as $item) {
parse_str($item->link, $params);
$coords = split(",", $params['xy']);
$data = array($coords[1], $coords[0],
(string)$item->title);;
$output[] = $data;
}
return $output;
}
function write_map_script(array $points) {
// center map on the middle result and draw
if (count($points) > 0) {
$middle_point = $points[count($points) / 2];
$js_middle = <<<JAVA_SCRIPT
var points = new YGeoPoint($middle_point[0], $middle_point[1]);
map.drawZoomAndCenter(points, 16);
JAVA_SCRIPT;
foreach ($points as $id => $obj) {
$map_point_name = addslashes($obj[2]);
$js_end = <<<JAVA_SCRIPT
var point$id =
new YGeoPoint($obj[0],$obj[1]);
var current_marker = new YMarker(point$id);
current_marker.addLabel('$id'),
current_marker.addAutoExpand(
'<div class="mp">$map_point_name</div>');
map.addOverlay(current_marker);
JAVA_SCRIPT;
$js_middle .= $js_end;
}
}
echo $js_middle . $js_end;
}
$points = get_quakes();
?>
<html>
<head>
REST servicesearthquakes feed<script type="text/javascript" src="http://api.maps.yahoo.com/ajaxymap?v=3.0&appid=your_api_key">
</script>
<style>
#mapHolder {
height: 700px;
width: 700px;
}
</style>
</head>
<body>
<div id="mapHolder"></div>
<script type="text/javascript">
var map = new YMap(document.getElementById('mapHolder'), YAHOO_MAP_REG);
map.addZoomShort();
map.addPanControl();
<?php write_map_script($points); ?>
</script>
</body>
</html>

And the output would look like:

Earthquakes and Yahoo MapsREST servicesunserialize() method, using

Mashups

A mashup is an application that combines multiple data sources into a single application. The rise of REST style applications available on the Internet enhanced the interest on Mahup applications as well.

Almost all examples that were given in this chapter could be considered mashup style applications. As an example, we combined the BBC news feeds with Yahoo news search to locate related news items.

Mashing up map data with other location related data is a very popular breed of applications today. The local search application and the earthquake application examples that we explored in this chapter fall into that category.

If you want to build mashups using the techniques that were introduced in this chapter, you can find information on publicly available information from programmableweb.com website. See http://www.programmableweb.com/apis/directory/1?sort=mashups for more information. This website has a very nice categorization so that you can find the kind of web service that you are looking for with ease. As an example, if you want weather information services, go to the weather link on the left-hand side menu.

PHP Web 2.0 Mashup Projects: Practical PHP Mashups with Google Maps, Flickr, Amazon, YouTube, MSN Search, Yahoo! is a book on mashup technologies from PACKT Publishing. You can find more information on this book from http://www.packtpub.com/php-web-20-mashups/book.

Summary

In this chapter we looked into some of the real world applications and learned how to combine multiple service interfaces to build value added custom applications.

In previous chapters, we have seen how to access Flickr API. In this chapter, we saw how to use RSS or ATOM feeds, Yahoo search API, and Yahoo maps API.

With the know-how you gained so far in this book, you could build very powerful value added applications like mashups using publicly available REST style services. The concepts covered so far include:

  • Using correct HTTP method to retrieve data from services

  • Using XML parsers for building requests and parsing responses

  • Consume XML feeds, example RSS or ATOM feeds

  • Steps involved in understanding a service API, both technical and non-technical

  • Best practices to be followed in the prototyping phase

  • Abstracting out re-usable functionality into utility classes or libraries

  • Combining multiple service iterations to build value-added applications

  • Mixing up PHP and JavaScript

  • Dealing with message formats other than XML such as serialized PHP

  • Working with application specific details such as request/response formats and extracting the information we want from the response using PHP functionality

  • A brief introduction to Mashups

In the next chapter, we will explore how to design a RESTful service from ground-up, this will help you to understand how to apply REST principles and design your own services. We will also implement the designed service using

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset