Make Yahoo! Web Service REST Calls with PHP

There are several ways to make Yahoo! Web Services REST requests using PHP. In this HOWTO, we discuss and demonstrate some recommended methods. This page contains these sections:

Overview of Making REST Requests With PHP

REST requests are modelled after the way a web browser sends requests to a web server. So, when we use the PHP programming language for REST requests, our PHP scripts mimic the way a web browser interacts with a web server. PHP, being an extremely flexible and feature-rich language, provides a number of different mechanisms you can choose from to make your REST requests. The ones we recommend are:

Depending on your web server environment, one or both of these functions may be desirable. file_get_contents is the simplest method and is especially good for very short scripts. Its main drawback is that it does not let you do HTTP POST calls. If the web service request requires HTTP POST, we recommend that you use curl. curl is a PHP extension that is widely used for making Web services requests. It offers a lot of control over network transport options and is especially convenient if you are making secure HTTPS requests.

Most Yahoo! Web Services REST requests mimic HTTP GET requests, but a few use HTTP POST, so, in this HOWTO, we provide sample code for both HTTP GET and HTTP POST requests when applicable.

Yahoo! Web services return XML data. Some can also optionally return JSON and Serialized PHP data. For information about the various Yahoo! Web Services, see the documentation at the Yahoo! Developer Network. The documentation on Constructing REST Requests can help you put together the parameters for a Yahoo! Web Services request if you are unfamiliar with the REST syntax.

For example, here's a request from Yahoo! Search web search service for the keyword "persimmon" that returns ten results:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=persimmon&results=10

By default, Yahoo! Web Services return XML output. With the output=json parameter, you will get JSON output instead:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo &query=persimmon&results=10&output=json

With the output=php parameter, you will get Serialized PHP output:

http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=persimmon&results=2&output=php

Prerequisites

Both file_get_contents and curl have configuration prerequisites.

file_get_contents is only available in PHP 4.3 and later versions. In general, we recommend that you run PHP version 4.3 or later, so that should not be an issue. However, for security reasons, your PHP installation must have fopen wrappers enabled in order to access URLs using file_get_contents. If fopen wrappers is not enabled, you will not be able to use file_get_contents for Web services requests.

curl is a PHP extension that must be loaded in your PHP configuration file, called php.ini. Editing this file normally requires administrative privileges on your server.

To see whether curl is installed and active in your PHP build, whether fopen_wrappers is enabled, and what version of PHP is running, call the phpinfo function and browse the output:

<?php
    echo phpinfo();
?>

Note: To find your current fopen_wrappers settings, look for the string allow_url_fopen in the output.

Making Requests With file_get_contents

PHP's file_get_contents function lets you easily fetch a URL and return the contents as a string. Since file_get_contents handles all of the web server interaction behind-the-scenes, you must use it for HTTP GET requests. However, only a few lines of PHP are needed to make a request. The documentation on www.php.net for file_get_contents has the most definitive description of its usage and parameters.

For HTTP GETs, REST requests take the form of a URL, so any parameters that might contain spaces, or other characters that are illegal in a URL, must be encoded using PHP's urlencode function. For example, to make a request using Yahoo! Search Web Services, encode the query parameter as follows:

$request =  'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query='.urlencode('Al Gore').'&results=8'; 

The actual request is achieved by invoking the file_get_contents function with the URL as the parameter:

$response = file_get_contents($request);

A complete code sample is available here.

Making Requests With curl

The curl library is used for making network requests from a high-level programming language. It greatly simplifies the code necessary to make HTTP GETs and POSTs and offers developers a lot of network connection options.

GET Requests With curl

Making network requests using curl is straightforward. You first initialize your curl session, providing the request URL as a parameter. The function curl_init returns a session handle for you.

$request =  'http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query='.urlencode('Al Gore').'&results=8'; 
    $session = curl_init($request); 

You then set any curl options that you might need. curl options are listed here. In this case, we tell curl that we don't want the HTTP headers returned, but we do want the request data returned:

    curl_setopt($session, CURLOPT_HEADER, false); 
  curl_setopt($session, CURLOPT_RETURNTRANSFER, true); 

The response is returned by running curl_exec on the session handle. After executing the session, we close it with curl_close:

    $response = curl_exec($session); 
  curl_close($session); 

A complete code sample is available here.

POST Requests With curl

A POST request with curl is slightly more complicated than a GET because the request parameters must be sent separately from the the request URL. To illustrate, we use the Content Analysis web service which requires that you use HTTP POSTs for your requests.

We first separate the request URL and parameters into separate variables:

// The request URL prefix 
    $request =  'http://search.yahooapis.com/ContentAnalysisService/V1/termExtraction'; 
    // The request parameters 
    $appid = 'YahooDemo'; 
    $context = 'Italian sculptors and painters of the renaissance favored the Virgin Mary for inspiration'; 
    $query = 'madonna'; 
    // urlencode and concatenate the POST arguments 
    $postargs = 'appid='.$appid.'&context='.urlencode($context).'&query='.urlencode($query);

The curl session is initialized using just the URL prefix as a parameter:

  $session = curl_init($request); 

The various curl options need to be set specifically for a POST:

    // Tell curl to use HTTP POST
    curl_setopt ($session, CURLOPT_POST, true); 
    // Tell curl that this is the body of the POST
    curl_setopt ($session, CURLOPT_POSTFIELDS, $postargs); 
    // Tell curl not to return headers, but do return the response
    curl_setopt($session, CURLOPT_HEADER, false); 
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
  

We then run curl_exec to execute the POST and then close the session:

 
    $response = curl_exec($session); 
  curl_close($session); 

A complete code sample is available here.

Error Handling

Yahoo! offers many REST Web services but they don't all use the same error handling. That's because some of Yahoo!'s Web Services came from companies that Yahoo! acquired, such as Flickr and Upcoming. These companies already had their own Web services error handling in place. However, most Web services that we developed in-house, including all of our Yahoo! Search Web Services, use the documented error handling.

The documented error handling returns error information using the HTTP status code returned in the HTTP response header.

Using curl

The HTTP status code is available via curl. To access the HTTP header, set the curl option for the header to true:

curl_setopt($session, CURLOPT_HEADER, true); 

Then, to extract the status code from the heade, use a regular expression:

sectionSubH
$status_code = array(); 
    preg_match('/\d\d\d/', $response, $status_code); 

The code is interpreted based on the documented error handling:

switch( $status_code[0] ) {
       case 200:
       // Success
       break;
       case 503:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 503. That means: Service unavailable. An internal problem prevented us from returning data to you.');
       break;
       case 403:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 403. That means: Forbidden. You do not have permission to access this resource, or are over your rate limit.');
       break;
       case 400:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 400. That means:  Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
       break;
       default:
       die('Your call to Yahoo Web Services returned an unexpected HTTP status of:' . $status_code[0]);
    }
    

Since the HTTP Header is returned along with the rest of the data, we have to remove the header and just extract the data we want:

// Get the XML from the response, bypassing the header 
    if (!($xml = strstr($response, '<?xml'))) { 
       $xml = null; 
    } 

A complete code sample is available here.

Using file_get_contents

With file_get_contents, the HTTP status code can be retrieved from the PHP global array $http_response_header. The array contains one HTTP header per array element and is set automatically after you execute file_get_contents. After making the request, you can retrieve the HTTP status as follows:

list($version, $status_code, $msg) = explode(' ', $http_response_header[0], 3);

The code is interpreted based on the documented error handling:

switch( $status_code ) {
       case 200:
       // Success
       break;
       case 503:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 503. That means: Service unavailable. An internal problem prevented us from returning data to you.');
       break;
       case 403:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 403. That means: Forbidden. You do not have permission to access this resource, or are over your rate limit.');
       break;
       case 400:
       die('Your call to Yahoo Web Services failed and returned an HTTP status of 400. That means:  Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
       break;
       default:
       die('Your call to Yahoo Web Services returned an unexpected HTTP status of:' . $status_code[0]);
    }
	

A complete code sample is available here.

For More Information

For more information on using PHP with Yahoo! Web Services APIs, see the Yahoo! Developer Network PHP Developer Center.