Learn to use the World Bank API 2.0

This is a simple tutorial on how to access and query the World Bank API 2.0. It uses the PHP programming language. This example assumes the following: We will be building a simple application which allows a user to get photos for a selected country.

Download The Code

To get started, please download the code and put it into your web server directory.

Making Your First Call

By default, the World Bank API returns structured XML (as described by the API documentation). Currently the API supports two formats: XML and JSON. To make a call using PHP, first we need to be able to contact the API server and then be able to interpret the response. Thanks to PHP5's simpleXML library, we have a easy-to-use solution right out of the box. Let's get started.

1. Getting Started
<?php    
    error_reporting
(E_ALL);
    
    
$apiKey "xxxxx";
    
    
/**
     * Checks whether the call to the API returned an error 
     *
     * @param SimpleXMLElement $xml
     */
    
function api_call_returned_error($status_code) {
      
      if(
$status_code 200) {
        return 
true;
      }
          
      return 
false;
    }
    
   
/**
    * Return current API URL
    */
    
function api_get_url() {
        return 
"http://api.wbext.com/v2";
    }
?>
<html>
    <head>
        <title>Example using World Bank API</title>
    </head>
    <body>
    <?php
      
      
// Set url to make country query into the API
      
$url api_get_url()."/countries?per_page=250&api_key=".$apiKey;
      
      
// Make the call to the API, which returns valid XML
      
$xml = @simplexml_load_file($url);
      
      
// Retrieve HTTP status code
      
list($version,$status_code,$msg) = explode(" ",$http_response_header[0], 3);

      
// Check if the API call failed
      
if(api_call_returned_error($status_code)) {
         echo 
"Could not fetch country list. Error #" $status_code " - " $msg;
         exit;
      }
    
    
?>
Summary: Details:

Make sure to change the $apiKey variable to your API Key, otherwise this example will not work. So what are we doing here? First, we define a function api_call_returned_error which, as you might imagine, checks to see if an API call returned an error. All API calls which return an error information using the HTTP status code returned in the HTTP response header. Documented error codes
<wb:error xmlns:wb="http://www.worldbank.org" >
  <wb:message id="199"  key="Unexpected error" >
    An unexpected error was encountered while processing the request.
  </wb:message>
</wb:error>
Next, we set the API url to http://api.wbext.com/v2 and since we want to retrive a list of countries in the API, we access the countries call. We also tell the call to return the first 250 results, to ensure we get a complete listing of countries. Lastly we need to provide our API key, defined at the top of the file in the $apiKey variable so that our account is identified by the system.

To make the call we use the simplexml_load_file function to retrieve the contents of the API call. A description of the SimpleXML library is outside the scope of this tutorial, so if you are unfamiliar with it, please see the official simpleXML documentation.

Once we have made the call to the API, we use the api_call_returned_error function defined at the top of the file to check for any errors.

Setting Up The Country Drop Down

Now that we have retrieved a list of countries from the API, we want to give the user the ability to select a country. A simple HTML drop down seems to be in order.

2. Building The Country Drop Down

<form action="<?php echo $_SERVER["PHP_SELF"?>" method="POST">
  <b>Select A Country: </b><select name="country">
   <?php                
     
foreach($countries as $country) {
      if(
$country->iso2Code == $_REQUEST["country"]) {
         echo 
'<option value="' $country->iso2Code .'" SELECTED>' $country->name '</option>';
      }
      else {
         echo 
'<option value="' $country->iso2Code .'">' $country->name '</option>';
      }                        
     }
   
?>
</select>
<input type="submit" value="Get Photos" />
</form>
Summary: Details:

So what have we done here? We've simple built an HTML form that submits back to itself. The automatically populated PHP variable $_SERVER["PHP_SELF"] takes care of that for us. Then we simply use a foreach loop to cycle through all the countries that were returned from our API call, slowly building an HTML drop down that the user can use to choose a country.

Why the complicated if statement inside the loop? This might not be obvious until you've submitted the form for the first time, but it automatically selects the country that the user chose in his last form submission. This gives some visual feedback to the user as to which country he selected when the page reloads on form submission. If this is confusing to you, feel free to remove the if statment and replace it with the echo statment in the else section of the for loop.

Notice that the two echo statements are identical, except that the first one includes the HTML option tag attribute SELECTED.

Processing The Form Submission And The Retrieving Photos

Great, we've set up a form that allows the user to select the country he is interested in. So how do we use this information to retrieve relevant photos?

3. Processing The Form Submission

<?php        
 
if(count($_REQUEST) > && !empty($_REQUEST["country"])) { // if the user submitted the form
                 
 // Set url to make photos query into the API, based on the country the user selected
 
$url api_get_url()."/photos?country=".$_REQUEST["country"]."&api_key=".$apiKey;
?>                
    <b>Query url:&nbsp;</b><?php echo $url;?></br>                
<?php
                
 $xml 
simplexml_load_file($url); // make the call to the API, which returns valid XML
        
 // Retrieve HTTP status code
 
list($version,$status_code,$msg) = explode(" ",$http_response_header[0], 3);

 
// check if the API call failed
 
if(api_call_returned_error($status_code)) {
    echo 
"Could not fetch photos for " $_REQUEST["country"] . ". Error #" $status_code " - " $msg;
    exit;
 }

 
$photos $xml->children("http://www.worldbank.org");
        
 if((integer) 
$xml["total"] == 0) {
    echo 
"No photos found for " $_REQUEST["country"] . ".";
 }
}
else {
 
// loop through photos returned                    
 
foreach($photos as $photo) {                        
     echo 
"<a target='out' href='" $photo->lowResURL "'>"// link to the higher resolution image
     
echo "<img src='" $photo->thumbURL "' vspace='5' hspace='5' />"// print the image to the screen
     
echo "</a>";
 }                    
}
?>
Summary: Details:

The first line if(count($_REQUEST) > 0 && !empty($_REQUEST["country"])) checks to see if the form has been submitted. How? We know the form has been submitted if at least one request variable has been included. The $_REQUEST array is an automatically populated array in PHP that includes all variables submitted via the post and get form methods.

Why do we have to check if the form has been submitted? Remember, we are using the same script both before the user has selected a country and after, so we can't assume that the user has chosen a country everytime the page loads.

The next few lines should be familiar to you at this point, since they are very similar to the code we used to query the API for a list of countries above. The only difference is that the query URL has changed to use the photos call, since this time we are looking to find a list of photos for the country the user has selected.

After checking for any errors in the API call, the first thing we want to do is check to see if there were any photos found for the country. We do this with the (integer) $xml["total"] == 0 line, which checks whether the total attribute for the photos is greater than zero.

If we have photos, then we loop through the photos and output each photo to the screen as a thumbnail, where each thumbnail also acts as a link to a higher resolution version of the image. For more information on the data returned via the photos call, see the API documentation.

Conclusion

As you can see, using the World Bank API is very simple. In just 70 lines of code, we were able to build a very useful application with very real relevance.

For more information on how to use the API, please use the following links: