Consuming the Yahoo! APIs
All the standard Yahoo! APIs are RESTful in nature; data is accessed via standard HTTP requests, where query parameters are passed to the API through the URL. What this means is that you can fetch data from the API as easily as you would fetch the HTML source of any web page, and you can test requests using any browser that will render XML. Take this sample URL:
http://api.search.yahoo.com/WebSearchService/V1/webSearch?
appid=YahooDemo&query=SitePoint&results=2
Try it out -- visit the URL in your browser and take a look at the XML output. Since the output is XML, however, we need to parse the response XML with PHP in order to make use of it. A number of classes and XML parsing functions are readily available for PHP, but Yahoo! goes a step further: it provides an option to get all the output data in serialized form. This means that you can quickly fetch the data, run it through the unserialize
function and start working with the data immediately. To get PHP serialized output, just append &output=php
to the query string. Here's a simple script that searches the web for "SitePoint" using the web search API, all in three effective lines of code:
$output = file_get_contents(
'http://api.search.yahoo.com/WebSearchService/V1/'.
'webSearch?appid=your-app-id-here'.
'&query=SitePoint'.
'&results=2'.
'&output=php'
);
$output = unserialize($output);
echo ''.print_r($output,TRUE).'
';
?>
Examining this snippet, we see that we first fetch the data in PHP format using the file_get_contents
function, then convert it to an associative array with unserialize, before outputting a dump of the array with print_r
. I should note here that to be able to use file_get_contents
to open a URL requires the allow_url_fopen
setting to be enabled in php.ini
. Check with your host if you're not sure if this setting is in place. Let's take a look at the output. $output['ResultSet']['Result']
contains the data we're looking for. Here's a snippet of the first search result:
[Title] => SitePoint : New Articles, Fresh Thinking for Web Developers and Designers
[Summary] => Network of sites that provice information, tools, and resources for internet-focused businesses and web developers, including WebmasterBase.com, eCommerceBase.com, and PromotionBase.com.
[Url] => http://www.sitepoint.com/
Compare this with the first result for the term "SitePoint" on the official Yahoo! Search site and you'll see it's the same.
Result for a search on (click to view image)
All the data you would normally get through a Yahoo! search is available through the API! Forget messy screen scraping -- Yahoo! makes it easy to get the search results directly. With another few lines of code, we can turn our array into a full search results page. You can probably already see how to make a search engine with the Yahoo! web search API here -- it's that simple! Building your own search engine from scratch would usually involve buying a data centre and spending years spidering the web, but Yahoo! provides all the data free of charge (with usage restrictions, of course). You may have heard of rollyo.com, a site that lets you create your search engine. Well, Rollyo is built using the Yahoo! APIs. With just a few lines of PHP, we can query the Yahoo! web search API, parse the API output, extract the data, format it and output it -- that's a lot of power to have available at your fingertips.
Most of the Yahoo! APIs are just as easy to use as Web Search, and Yahoo! provides a guide to constructing REST queries if you need further information about fetching data from the APIs. Each API method has a documentation page outlining the parameters available, return values, possible output formats (XML, PHP, etc.) and potential errors. It should be noted that all parameters are URL encoded, so php code
should become php+code
, or the API may return unexpected output. PHP's inbuilt urlencode
function is sufficient for this task. As a general guide, each service has a base URL something like the following:
http://api.search.yahoo.com/WebSearchService/V1/webSearch
Each service requires certain parameters, one of which will be your application ID, and most services will have a query parameter. In the previous example search, we use the parameters appid
, query
, results
and output
. In this case, appid
is the application ID, query
is what we are searching for ("SitePoint") and output
is the format we want the API output in (php
for serialized PHP form, optional). The results
parameter is optional, however I use it here to limit the output to two search results in order to reduce server load. If you don't need the standard 10 results, limiting the output through the results parameter is highly advisable. We append a question mark and the parameters to the URI, separating each parameter with an ampersand (&
) and using the standard option=value
format, just like any other HTTP request.
So now that you've had a gentle introduction to the usage of Yahoo! APIs, how they behave and what they provide access to, let's take things up a notch and look at how we can actually put these APIs to good use.
PHP 5 and the Yahoo! APIs
PHP 5 has a number of features that help us make effective use of the Yahoo! APIs. PHP 5's improved internal OOP support enables developers to efficiently build applications, and we can take advantage of this by using classes to rapidly develop libraries that make use of the Yahoo! APIs. The introduction of the file_get_contents
function allows easy querying of the APIs, and as I mentioned before, PHP has the added advantage of receiving serialized output from most of the APIs with inbuilt parsing functions. Even though the HTTP extension is available in PHP 5, we won't need it for low-end API consumption. PHP 5 developers can easily query the APIs, parse the output, deal with errors and make use of the data without too much trouble.
Quick and Easy Mashups
To demonstrate the power of the Yahoo! APIs, we're going to put together a very simple, practical application using PHP 5 and various Yahoo! APIs. What we want to do is query the local search API for data from Yahoo! Local, where users discuss and rate local attractions, businesses and so on. Then we'll place that data on a map, showing geographically where those attractions are located.
YahooAPI Client Class in PHP 5
To make our lives easier, we're going to use a PHP class that helps us to query the Yahoo! APIs. The base class needs to have the following functionality:
- Set the web service to be used.
- Add parameters to the request.
- Execute the call to the remote API.
- Fetch the output.
I've built a very simple, extensible class to do just this, called YahooAPI
-- take a look in the code archive for this article. While I won't go into the details of the YahooAPI
class, using it is very easy. In the previous example we searched for "SitePoint" on the Web. The same task can be achieved very easily with the class:
$api = new YahooAPI();
$api->setAppID('your-app-id-here');
$api->setService('http://api.search.yahoo.com/WebSearch
Service/V1/'.
'webSearch');
$api->setParam('output','php');
$api->setParam('query','SitePoint');
$api->setParam('results','2');
$output = $api->doAPICall();
This is exactly the same as the previous search example, except that now we use the client class. In this case, using the class is more verbose, but with more complex and repeated calls to the API, using the class can save time and simplify maintenance.
Manipulating Data from API Calls
Now that we have everything we need to get to work, I'll show you how to easily manipulate data from the Yahoo! APIs.
Let's use our new YahooAPI class to search for 'Pizza' in 'Palo Alto, CA' using the Local Search API. Take a look at the documentation page for the latest version of the local search API. This is the base URL for the service:
http://local.yahooapis.com/Local
SearchService/V3/localSearch
So we'll call the setService
method of the YahooAPI
class and give it the base URL. Looking through the request parameters in the documentation, we'll need to submit the 'appid'
, 'query'
and 'location'
parameters. After we set the required application ID, we then need to choose a location -- we'll use a city and state for now -- and a query. Let's say we're searching for 'Pizza' in 'Palo Alto, CA'. In simple, procedural PHP code using the YahooAPI
class, the search would look something like this:
$api = new YahooAPI();
$api->setService('http://local.yahooapis.com/LocalSearch
Service/V3/'.
'localSearch');
$api->setAppID('your-app-id-here');
$api->setParam('output','php');
$api->setParam('query','pizza');
$api->setParam('location','Palo Alto, CA');
$output = $api->doAPICall();
The call to the API here is the same as fetching
http://local.yahooapis.com/LocalSearch
Service/V3/localSearch?appid=your-app-id-here&
query=pizza&location=Palo+Alto,+CA
through any method, so take a look at that URL in your web browser. Clearly the information we're looking for is within each
node, and all
nodes are within one big
node. The PHP version that we're fetching has exactly the same structure as the XML, except that it's in an easily usable array. After fetching all that data into the $output
variable, all we have to do is iterate over the $output['ResultSet']['Result']
elements and fetch the data we need. Try it out -- add the following code after the previous example and run it on your web server:
foreach($output['ResultSet']['Result'] as $result) {
echo $result['Title'].'
';
}
You should receive something like the following output:
Patxi's Chicago Pizza
Papa Murphys Pizza Take & Bake
New York Pizza
Round Table Pizza Palo Alto
Domino's Pizza
California Pizza Kitchen
Pizza My Heart
Ramonas Pizza
Round Table Pizza Palo Alto
Spot A Pizza
No comments:
Post a Comment