Beginner’s guide to working with APIs

WebsitesCategory
5 min read
Douglas Karr

When you type an address or submit data via a browser window, you're making a server request via the user interface. This methodology has a parallel in the programming world known as the API — or Application Programming Interface.

Instead of sending a request and receiving data via HTML and having the results displayed as a web page, though, programs using APIs send the request and receive the result in a format like JSON (JavaScript Object Notation) or XML (EXtensible Markup Language), which can then be used directly inside of other programs.

Here's a simple example: finding the location of a user based on their IP (Internet Protocol) address. Let's pretend I'm in Arizona and I visit your site. You want to display a message to me that's specific to my geographic location. You can use the API of the Free Geo IP service:

Launch your business in minutes with GoDaddy Airo™

If you just paste that request in your browser, you'll see the response, in JSON:

{"ip":"97.74.104.218","country_code":"US","country_name":"United States","region_code":"AZ","region_name":"Arizona","city":"Scottsdale","zip_code":"85260","time_zone":"America/Phoenix","latitude":33.6119,"longitude":-111.8906,"metro_code":753}

cURL request in PHP

But what if you wish to do that programmatically? PHP offers a method called cURL that's common to virtually any server installation. Basically, cURL makes the request and then provides a response that you can then work within your code.

In the example above, a cURL request in PHP might look like this:

$apiurl = 'http://freegeoip.net/json/' . $_SERVER["REMOTE_ADDR"];

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $apiurl);
 curl_setopt($ch, CURLOPT_HEADER, false);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
 $response = curl_exec($ch);
 curl_close($ch);

 $data = json_decode($response);

echo "Our visitor is from ".$data->city;

You can call external APIs from many popular systems, including WordPress.

WordPress methods for retrieving data from APIs are available via wp_remote_get and wp_remote_post.

If you put that PHP code from above directly in your WordPress page template, it will run without any edits. However, I'd advise against writing your code this way.

Working with external APIs in WordPress

WordPress, as usual, has provided us with a much safer, cleaner and easier method for working with external APIs.

  • wp_remote_get — Utilize a GET method to retrieve data via an API or web service.
  • wp_remote_post and wp_safe_remote_post — Utilize a POST method to retrieve data via an API or web service. The second safe method ensures that data is securely passed between servers.

Our code above is simplified:

$apiurl = 'http://freegeoip.net/json/' . $_SERVER["REMOTE_ADDR"];
$response = wp_remote_get ($apiurl);
$data = json_decode($response['body']);
echo "Our visitor is from ".$data->city;

This method has an added feature of enabling us to view and program the response headers. That can come in very handy when troubleshooting problematic or blank responses from APIs.

Applying specific arguments

Of course, there are specific arguments that you can apply to your request as needed for dealing with the specifics of calling external APIs:

$args = array(
 'timeout' => 5,
 'redirection' => 5,
 'httpversion' => '1.0',
 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ),
 'blocking' => true,
 'headers' => array(),
 'cookies' => array(),
 'body' => null,
 'compress' => false,
 'decompress' => true,
 'sslverify' => true,
 'stream' => false,
 'filename' => null
);

$response = wp_remote_get( $url, $args );

Tips on working responsibly with APIs

While many services on the Internet have APIs, you can run into problems if your code isn't well-written and instead aggressively accesses their servers! Great APIs will typically have authentication, security, throttling (applying a maximum number of requests per time period), and caching. You should be a responsible API consumer and always look for opportunities to enhance your code.

In the example above, I might want to save that IP address and the results on my server for a few days. This way, each time the visitor opens a new page in their session, I don't keep requesting the same data over and over from Free Geo IP (which has a 10,000 request per day threshold on its API). Instead, I can request the data once and then store it for a period of time. Each time the visitor returns, I can check to see if I have their IP address information, use it, and forego requesting the same IP address again from the Free Geo IP service.

In the TweetThis Shortcode plugin, we save the shortened URL as a post variable so that we don't have to submit it over and over with each visitor on the site.

If you'd like to research APIs that you might be able to utilize, visit ProgrammableWeb, a site dedicated to documenting and researching APIs. They've got a database of over 14,000 APIs. Happy coding!