An Intro to APIs


What’s an API?

'Application Programming Interface' is a pretty scary title for something that’s actually pretty straight-forward -- applications need to talk to one another. When you use an app like Instagram and you press a button that allows you to sign in using Facebook, what’s really happening is that the app you’re using is talking to Facebook, and requesting some information to show you.

In order for it to ask for and retrieve the right information, it uses that app’s API. It doesn’t need a pretty user interface with bright buttons and a nice layout like we would; programs don’t need buttons. Instead, an API will send back data in a form that’s easily read by your computer. That API describes what you can do with that data, how it can be used, what formats it will accept, and what it returns as output for other programs to work with.

What do APIs do?

Web APIs allow developers to integrate services into their smaller apps; every time you register for a new app using your Facebook or Twitter account, the developer has used an API. Whenever you see a Google map on a restaurant’s website showing you where you can find them, that’s an API. Have you searched for and watched a YouTube on a site that wasn’t Youtube itself? An API! You get the idea.

These types of APIs allow developers to use some of the functionality of other applications in their apps, provided they follow the documentation outlined by the people who made it. It makes it possible for Google to let you have an awesome map on your website without handing over their entire codebase.

APIs are still useful in open source; you can pick and choose what parts of an application you want to use without trawling through an entire codebase, and avoid any licensing issues if you want to use your app commercially.

For code newbies in particular, APIs are a great way to get a lot of interesting functionality into simple apps. You don’t have to understand how to do sentiment analysis yourself to exploit Twitter’s API, and this and many other advanced techniques are accessible to many more people.

A web service API does things like:

  • allow a programmer to access information from another web service
  • allow a programmer to use a web service in their own application
  • allow a programmer to change or update data on another application

Are APIs only for web services?

There are many different types of API, including ones for web services, operating systems and hardware, and you can find out more about them here. There are also APIs that interact with the backend of your own code, which you can write however you like of course, but the expected format is usually JSON. For this article I’m going to concentrate on what code newbies will usually run into: web service APIs that also return JSON.

First let’s review some terminology:

What’s a query?

A query is another term for the request you make. To make a query, you need to specify an endpoint. An endpoint is basically just a URL you can access for different stuff.

What is an API call?

Whenever you want something from an API, you need to make a request to it, or in other words, make an API call. Web service APIs are usually free, though they generally have restrictions. For example, APIs often have a limit of how many times you can call them. APIs limit calls so that they aren’t overwhelmed with too much traffic.

Example: Twitter’s API

We’re going to look at Twitter’s API to demonstrate how APIs work. Twitter provides a REST API which will serve our needs well. Let’s look at the Twitter API docs and see what kinds of things we can do.

twitter_api.png

What kinds of functionality do you see provided by the API?

Twitter’s REST API contains lots of various endpoints to achieve whatever desired functionality a developer wants. Remember, an endpoint is a URL that your app can go to to talk to the API and either send or request information. If you need a list of users, you might send a GET request to a certain endpoint, like /users and that would return a list of users. If you needed a specific user's data, what endpoint do you think you’d use? Go check Twitter’s docs and find out! The standards for how these requests are made are collected in different specifications, the most common today being the REST (representational state transfer) architecture.

We can use one of two verbs with those end points, GET and POST. These verbs decide what type of request is sent. If we use GET with an endpoint, we’re usually asking for information. For instance, sending a GET request to the statuses/user_timeline endpoint will get us a user’s most recent tweets, as a JSON object. When we make a POST request, we’re generally making a change to a database. If we send a POST request to the account/remove_profile_banner, what change do you think we’re making? What would change in our database?

Because we are just dealing with URLs, anyone from anywhere on the web can access them. This is fine in some cases, but when dealing with things like a Twitter account, it would be really bad if anybody in the world could hit an API endpoint and post tweets to your account. To solve this problem, Twitter uses a method of authentication called OAuth. OAuth is a huge topic in itself, but basically all that we need to know for now is that to actually use Twitter’s api, a developer must register an account and get a free api key to use, to prevent security breaches.

Every language has it’s own slightly different way of making API requests, and even within a language, there are different ways of doing it. Here is one way that we might call the Twitter API using Ruby’s HTTP class, a class that Ruby provides for http requests, from a command line program:

First let’s setup the URI where we’ll send a request to:

uri = URI('<a href="<a href=" https:="" api.twitter.com="" 1.1="" statuses="" user_timeline.json?="&=2" "=""></a><a href="<a href=" https:="" api.twitter.com="" 1.1="" statuses="" user_timeline.json?="&=2</a">')"></a><a href="https://api.twitter.com/1.1/statuses/user_timeline...</a>"><a">https://api.twitter.com/1.1/statuses/user_timeline...</a"></a> href="<a href="https://api.twitter.com/1.1/statuses/user_timeline...">">https://api.twitter.com/1.1/statuses/user_timeline...</a><a"><a href="https://api.twitter.com/1.1/statuses/user_timeline...">https://api.twitter.com/1.1/statuses/user_timeline...</a> href="<a href=" https:=" "="" api.twitter.com="" 1.1="" statuses="" user_timeline..."="">https://api.twitter.com/1.1/statuses/user_timeline...</a>"><a href="<a href=" https:="" api.twitter.com="" 1.1="" statuses="" user_timeline..."="">https://api.twitter.com/1.1/statuses/user_timeline...</a>"><a href="https://api.twitter.com/1.1/statuses/user_timeline...">https://api.twitter.com/1.1/statuses/user_timeline...</a></a">

Next we’ll setup the params we want to pass in:

params = { :screen_name => 'twitterapi', :count => 2 }

Which we’ll first encode:

uri.query = URI.encode_www_form(params)

And the we actually perform the request!

res = Net::HTTP.get_response(uri)

If it works, let’s see the response we get back:

puts res.body if res.is_a?(Net::HTTPSuccess)

Again, to get something like this working, we’d first need to setup authentication. But if it was actually working, it would return a large JSON object.

What’s JSON?

JSON stands for JavaScript Object Notation and is a way of storing data that’s organised and easy to access. It can be used by any language, JSON just requires that you format it in a specific way. JSON looks like this:

var jsonObj = {
  "key": “value”,
  "can_contain_any_variable_type": true,
  "even_arrays": true,
  "heres_an_array": [ 5, “cats”, null ],
  “and_objects_oh_my”: {
    "stuff”: 5,
    “other stuff”: “yey”
  }
}

It has key value pairs. A key is like a label or an identifier for a particular value. It can contain any of the data types that Javascript contains, and encloses strings in double quotes. To access values, you have to specify the key you want to target.

In our example, to get the value of the even_arrays key, you would use jsonObj.even_arrays. You don’t need to use the double quotes when you access the value. To access the values in an array, you just include the position in the array; jsonObj.heres_an_array[1] would return “cats”.

The json object returned by the Twitter api could contain a bunch of Tweets, which then we could loop through and output to a command line, or display on a website. If you are interested in playing with the Twitter API, this terminal program is a fun place to start, and can be used right away. So get started with APIs, and let us know what you think!