Intro to APIs

Beck Williams
Jul 28, 2017 · 7 min read

I’m still relatively new to the world of web development, but I’ve heard the acronym “API” enough times to know basically what they are, that they’re used literally all the time, and that it’s not uncommon to have only a vague idea of what the term means.

Save yourself some existential dread by reading this post!

API Appetizer

APIs are a lot like waiters at a restaurant. You sit down, they hand you a menu, and you give the waiter your order using the menu (ensuring your request is in a particular format that they know and understand). The waiter takes that request back to the kitchen, where there’s a lot going on behind the scenes: ingredients, recipes, cooking techniques, etc. At the end of the day, all you want is a meal in a format that you know and can easily digest (pun intended). The waiter is your connection from you and your menu item to your food, in the same way that an API is a connection from one application or its data to another.

To push the analogy further, cooking all your meals at home has some advantages but it can be time- and resource-consuming. In addition, Outback makes a better steak and deep-fried onion than you could — no need to reinvent the wheel! They also probably already have access to ingredients or tools that would be difficult for you to get on your own. Essentially ending up with a great dinner is easier and more reliable by ordering from a menu (using an existing solution to a problem) than it would be by doing all the work yourself. This is the purpose of an API.

Ok, but what does that actually mean on the web?

Let me give an example to explain. At my first hackathon, I wanted to create a simple app that functioned as a route finder for cyclists — cyclists who presumably wanted to avoid lots of hills, even if it meant going a little out of their way. Gathering all of the map, DOT, elevation, and GPS data to build this kind of app from scratch would have been close to impossible. This is a perfect use case for some APIs! Google already has all of this data, and their APIs are the waitstaff that can deliver it in a way that my application can read, interpret, and then present to the user however I like. Pretty neat!

You’ll see this kind of integration in applications you use all the time: any time you’re prompted to share a Medium article with your Facebook friends, whenever you see a section of Google Maps when writing a Yelp review, if you ever search for flights on Expedia and see data from Delta, Alaska, United, etc. APIs allow us to combine data from multiple applications into your own hybrid app, or create an app that enhances the experience of using someone else’s application.

Request and Response

Now that you have the right idea in mind, let’s talk nuts and bolts — how do APIs actually work?

Technically, API stands for “Application Programming Interface.” It’s a way for one program or app to interact with another in a defined way. Much like the way we order food at a restaurant, an application uses an API to communicate a request for data or a service to another application or database. A request is sent, and a response is received. The API is the menu and the middle-man who takes those messages back and forth.

More Acronyms!

HTTP — Hypertext Transfer Protocol

APIs are found in lots of different places and the term is used in different ways, but in this post we’re going to focus specifically on APIs that share application data over the Internet. While there are other transfer protocols that serve this purpose, like FTP and gopher, HTTP is by far the most widely used. So let’s talk a bit about HTTP so we can talk about HTTP APIs.

HTTP is a communication protocol used to send and receive webpages or other data files on the internet between clients and servers. A client may be a web browser, for example, and a server would be an application running on a computer hosting a website. The client sends an HTTP request message to the server, and the server processes the request, returns resources (like HTML files or other content) or performs some functions, and returns a response message back to the client.

This request-response process works using eight different HTTP verbs or methods that, like the name suggests, perform some action. These are: GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, and CONNECT. Most of the time when you’re surfing the web, your browser is using the GET HTTP method to “get” a resource from the Internet. When you submit a form, the browser is using POST to “post data” back to the server. As for the other methods, some browsers don't even implement them all (and only the first four matter to us right now, as you’ll see soon).

When an HTTP request is made using one of the above verbs, the server will return a response with the requested resources (if any) as well as an HTTP status code. These let the client know whether the request was successful or not and how to proceed. There are four different levels of status codes: 2xx=Success, 3xx=Redirect, 4xx=User Error, 5xx=Server Error.

CRUD — Create, Read, Update, and Delete

These are the four basic ways that we interact with data. These map directly to the first four HTTP methods GET, POST, PUT, andDELETE. Which brings us to…

REST — Representational State Transfer

REST, in short, is a term used to describe a standard way of creating web APIs, invented by Roy Fielding. It’s an architectural style that’s platform-independent (doesn’t matter if the client is a Mac, the server is Unix, etc), language-independent (C# can talk to Java can talk to Python…), standards-based (it runs on top of the HTTP methods mentioned above!), and it’s the most common type of HTTP API.

So what makes an API “RESTful”? There are six main constraints:

  1. The API must have a uniform interface. As mentioned, CRUD maps easily to the four HTTP verbs GET, POST, PUT, andDELETE. A RESTful API uses these methods to interface with the data, making for an easy-to-follow standard that helps streamline communication. REST APIs also use URLs to identify a resource in an API, as well as HTTP response codes in their responses.
  2. The API must be stateless. This means that all the information required to process a given request is contained within the request itself (as part of the URL, in query-string parameters, in the body of the request, in headers, etc). The server doesn’t need to know anything about previous requests in order to process the current request.
  3. The API must be cacheable. This means that individual responses must define themselves as cacheable or not in order to prevent the reuse of stale or incorrect data, and to enable reusing appropriate data to boost performance and scalability.
  4. The API must separate clients from servers. This means that, for example, clients don’t need to be concerned with data storage, and servers don’t need to know about the user interface or user state. Servers and clients can be replaced and developed independently.
  5. The API must be a layered system. This means that even if there are intermediary steps between the request and the response, the client doesn’t need to know about them or interface differently with them. These layers might be load-balancers, caching providers, security enforcements, etc.
  6. The API can optionally allow the client to run some code on demand. This means that instead of just returning data, a RESTful API might extend some logic or functionality from the server to the client.

Let’s look at a simple example.

At BV, we use data about our customer’s marketing partners in order to better find and give insights about the way their partners are advertising on their behalf. Since many of them manage their partners through a network, it makes sense for us to access all of that data straight from the source: that network’s API!

Let’s call this network NetworkN. Their API is RESTful, so we can interface with it in a predictable way.

First, because we only want a specific advertiser’s data at one time, we need what we call an Advertiser ID to specify that. We get that info from each customer:

advertiser_id = 12345

Next, we need the URL that identifies where the data we need is located, which was given to us by the API provider:

url = 'https://api.networkn.com/Reports/BrandVerityAPI.json?ADVERTISER_ID=%s' % advertiser_id

Like the rules of REST stated, all of the information required to process the request is contained within the request itself. The URL points to the API, finds the BrandVerityAPI within their Reports, sends an ADVERTISER_ID parameter signifying which advertiser’s data we want to see, and tells the API we want the response content returned to us in json.

Finally, NetworkN requires authentication to access their data, so we need a username and password:

username = 'username'
password = 'password'

We then take all of that information to send a GET request (using python and the Requests HTTP library) to the API. This looks something like this:

session = requests.Session()
response = session.get(url, auth=(username, password))

Next, we check the status code returned to us, and proceed as necessary by either parsing the json or handling the error, simplified here:

if response.status_code == 200:
response_json = response.json()
data = response.get('advertiser_data', None)

else:
response.raise_for_status()

# ...where response_json might look something like:
{
id: 1234,
advertiser_data: 'Advertiser 1',
email: 'email@email.com',
partners: ['Partner 1', 'Partner 2', Partner 3'],
}

Simple as that!

That’s not all, folks.

This post is very much just an introduction to web APIs. Check out some of these resources to learn more:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade