← home← blog

APIs

24 Jan 2013

I must hear the word "API" about 20+ times a day. However, I've noticed a few people recently on Twitter and email me asking "where do I begin with APIs?" or "how do I get started with APIs?". Well I'm hoping after reading this today, you'll 1. Know what an API is and 2. Not to be so afraid to just get stuck in with them!

I've tried to write this tutorial whilst trying to remember what concepts confused me when I first started with APIs. So if I've not explained something enough or left something out that you're struggling with, then let me know in the comments below or on Twitter - @benhowdle.

AP-what?

Without quoting Wikipedia or telling you what it stands for (because it's not really that helpful), I'm going to describe exactly what an API is and what it does in my own words:

An API is an exposed set of methods for a developer to use, not needing to know the working guts of a system.

People often associate APIs with things like Twitter or Facebook or Foursquare, services like that. But an API has much broader use, ie. If you use JavaScript you may well have used .pushState(), well if you have, then you've used the History API. PushState is a method of the History API.

Your arsenal

What do you need to use an API? What languages can I use? Answer: any.

From personal experience, I've used APIs heavily with only two languages; JavaScript and PHP.

For PHP, you'd want to use cURL, like so:

// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
	CURLOPT_RETURNTRANSFER => 1,
	CURLOPT_URL => 'http://testcURL.com/?item1=value&item2=value2'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

In JavaScript (jQuery for conciseness of code), you'd use $.ajax, like so:

$.ajax({
	url: "test.html",
	cache: false
}).done(function( html ) {
	$("#results").append(html);
});

So, $.ajax in JavaScript (jQuery) and cURL in PHP. That's it.

Cool story "bro", but how do I get my latest tweet?

The PHP way:

<?php
	function get_data($url){
		$ch = curl_init();
		$timeout = 5;
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
	
	function showTweets($username){
		$url='http://api.twitter.com/1/statuses/user_timeline.json?screen_name='.$username.'&include_rts=true&count=1';
		$obj = json_decode(get_data($url));
		foreach ($obj as $item) {
	    	    $tweet = $item->text;
		    echo '<p>My latest tweet: ' . $tweet . '</p>';
		}
		
	}
?>

And the JavaScript (jQuery) way:

$.getJSON("https://api.twitter.com/1/statuses/user_timeline/benhowdle.json?count=1&include_rts=1&callback=?", function(data) {
	$("#twitter").html(data[0].text);
});

HTTP Methods

So far we've dealt with reading data from an API, not sending it. Reading data is done through the HTTP method "GET". Sending data, or posting data, is done with the HTTP method "POST".

In PHP, we can easily send (POST) data to a remote service with the following code, taken from Execute a HTTP POST Using PHP CURL:

//set POST variables
$url = 'http://domain.com/get-post.php';
$fields = array(
            'lname' => urlencode($last_name),
            'fname' => urlencode($first_name),
            'title' => urlencode($title),
            'company' => urlencode($institution),
            'age' => urlencode($age),
            'email' => urlencode($email),
            'phone' => urlencode($phone)
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

And with JavaScript (jQuery) we can execute a POST in the following way:

var obj = {
	first: 'ben',
	last: 'howdle'
}

$.ajax({
    type: 'POST',
    url: 'destination.php',
    data: obj,
    success: function(data, textStatus, jqXHR) {
        // Handle a success state
    },
    error: function(jqXHR, textStatus, errorThrown) {
        // Handle an error state
    }
});

So now you can retrieve data from an API and send data to it as well.

Gotchas!

Now, you may be feeling a little more confident and rush to start pulling data from APIs using JavaScript, however, you may end up with an error in your Console of something like:

"XMLHttpRequest cannot load http://example.com Origin localhost is not allowed by Access-Control-Allow-Origin.".

What the hell?

Well this means that the API you're trying to grab data from hasn't enabled CORS (Cross Origin Resource Sharing), read more about CORS, so you have two options; 1. persuade the service to enable CORS or 2. use JSONP.

A simple modification to our above code and we can have JSONP added to our Twitter call, like so:

$.ajax({
	url: "https://api.twitter.com/1/statuses/user_timeline/benhowdle.json?count=1&include_rts=1",
	dataType: 'jsonp'
}).done(function( data ) {
	console.log(data);
});

Next steps

Create an API client

A Beginner’s Guide To jQuery-Based JSON API Clients

Build your own API

Create a RESTful Services API in PHP

Move to API centric development

API Centric Development

Learn about REST APIs

Representational State Transfer

Build a completely client-side web app communicating with a REST API

Future of Software Development Delivery

I'm available for hire

Hire me