Web pages are easy for people to read, but difficult for computers to understand. APIs are sources of data that are easy for computers to understand.

If I said, hey API, what’s your favorite musician? It might say something like

{
 'name': 'Operation Ivy'
}

Every API is different, but they usually involve going to a specific URL to get information. The URL might be something like

http://www.example.com/api/v3/dogs?color=brown

Different URLs might give different information. These URLs are called endpoints.

# Several example endpoints
http://www.example.com/api/v3/dogs?color=brown
http://www.example.com/api/v3/cats?color=black
http://www.example.com/api/v3/goats?color=white

An API is just a web page

Honestly, seriously, truly: an API is just a web page! (…most of the time)

Want to ask Spotify what Drake’s top tracks are? Check right here: https://api.spotify.com/v1/artists/4W9G3Vnt9eXWTo4VeOQkSa/top-tracks?country=US

While what’s on that page isn’t easy to read, you can read closely and probably figure it out. A computer just does it much more quickly.

Since you’re able to kind of read the response, it’s usually a good idea to test API requests in your browser before you really start coding with them - it’s also really useful for debugging errors!

Most modern APIs (including Spotify’s) give you something called JSON, which stands for JavaScript Object Notation. Even though it says “JavaScript” in the name, it’s a format that every programming language can easily understand. It’s more or less the same as a dictionary in Python.

Making a request

A Spotify API request to search for 80’s playlists might look like this:

https://api.spotify.com/v1/search?query=80s&type=playlist

API requests are usually built up of two parts, an endpoint and parameters.

  • Endpoint: /v1/search (it’s just a URL!)
  • Parameters: query=80s&type=playlist
    • query is 80s
    • type is playlist

Note that a ? is used to separate the endpoint from the parameters, but a & is used to separate different parameters!

If you want to know what endpoints and parameters exist for an API, you’ll want to read the documentation.

Fill-in-the-blank endpoints

You might also see documentation that notes an endpoint like one of these two

https://api.spotify.com/v1/artists/{id}/top-tracks?country=US
https://api.spotify.com/v1/artists/[id]/top-tracks?country=US

This is for the top tracks for a given artist, the {id} or [id] means fill in the blank with the id of the artist you want. You can use the search endpoint to discover Drake’s Spotify id is 4W9G3Vnt9eXWTo4VeOQkSa, and then use

https://api.spotify.com/v1/artists/4W9G3Vnt9eXWTo4VeOQkSa/top-tracks?country=US

to get his top tracks. Make sure you remove the [] or {}, and if it doesn’t work try visiting the URL in the browser - it might provide a helpful error message.

Dealing with API responses

90% of the time when you’re dealing with an API, you’re going to do something like the following.

# Import the requests library, which will access the API URL
import requests

# Have requests go fetch the URL and store it in 'result'
result = requests.get('https://api.spotify.com/v1/artists/4W9G3Vnt9eXWTo4VeOQkSa/top-tracks?country=US')

# The result is technically text, but you know it's 
# actually JSON, so you tell Python to process the JSON
# into a dictionary (since that's what JSON basically is),
# then store that dictionary inside of the 'data' variable
data = result.json()

# And now we can take a look at what we've got
# There will most likely be dictionaries and lists and
# strings and all sorts of stuff in there!
print(data)

# You'll probably want to look at the keys instead of
# everything all at once, to see what you can access
print(data.keys())

# Once we know some keys, we can poke deeper...
print("There are", len(data['tracks']), "top tracks")
for track in data['tracks']:
  print(track['name'])

The other 10% of the time when an API doesn’t work like this, you’re probably dealing with an “OAuth API”. They require you to prove who you are with each request, and require a lot more effort.

But even though you deal with each API similarly, every single API is different. They all have different endpoints, different formats, different everything. That’s where API documentation comes in handy.

Authentication and API keys

Sometimes you need to identify yourself to the API in order to ask it for data. This is called authentication. There are roughly three levels of security with an API.

Level One: No Authentication

Spotify’s Web API (generally) doesn’t care who you are. You use a URL and wham! you’re good to go.

https://api.spotify.com/v1/search?query=80s&type=playlist

Level Two: API keys

The Dark Sky API requires you to sign up with your email address and gives you an API key.

An API key is a semi-secret string of letters and numbers that identifies who you are each time you ask for data. That way if you make too many requests they can start asking you for money!

You generally don’t want to share your API keys with the world. I’ve faked API keys for the following urls, so opening them in a browser probably won’t work.

In the Dark Sky API, the API key 1074402c474e3dab67f7377e1f95519 is part of the URL.

https://api.darksky.net/forecast/1074402c474e3dab67f7377e1f95519/37.8267,-122.4233

Sometimes you’ll also see it in the parameters, like in the New York Times Article Search API, you can see key=1074402c474e3dab as a parameter.

https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=1074402c474e3dab&q=syria

Level Three: OAuth

The Twitter API (and Facebook’s, some of Spotify’s, and more) use something called OAuth.

OAuth is a lot more complicated than an API key - you wind up having an API key, access tokens, and a lot of extra legwork. For OAuth APIs it’s usually best to rely on a package for your language of choice (see the next section).

API packages

Instead of making the raw requests yourself (as above), you can usually find a library to do the work for you. For example, Spotify has the spotipy package (yes, that’s spotify but with a py Python shout-out at the end).

Let’s search for tracks by Weezer.

import spotipy
sp = spotipy.Spotify()
results = sp.search(q='weezer', limit=20)
for i, t in enumerate(results['tracks']['items']):
  print ' ', i, t['name']

You need to be careful when using these libraries, though! Sometimes they fall out of date if their owner doesn’t update them each time the API itself is updated. If that happens you might run into problems getting the data from the API even if your code is 100% correct.