View on GitHub

Computational Science in the Cloud Institute 2016

Introduction to Application Programming Interfaces (APIs)

In general an Application Programming Interface (API) establishes the protocols and methods for one piece of a program to communicate with another.

Some examples of APIs:

Web APIs

In this course, we will focus on web APIs (or HTTP APIs). These are interfaces that are exposed over HTTP.

HTTP - the Protocol of the Internet

HTTP is how two computers on the internet communicate with each other. In particular, our web browsers use HTTP when communicating with web servers running web applications.

The basics of the protocol are:

REST APIs

REST (Representational state transfer) is a way of building APIs for computer programs on the internet leveraging HTTP in following sense:

Open a web browser and navigate to: https://api.github.com

Exercise 1. What URL would we use to get a list of github users?

Exercise 2. Can you find a URL returning the details of your github account?

Exercise 3. Navigate to the URL that returns your followers.

Using the Python requests library

We’ll use the python requests library to interact with the github API programmatically. Open up a Jupyter notebook and follow along.

In order to do anything, we need to:

import requests

The basic usage of the requests library is as follows:

# make a request
response = requests.<method>(url=some_url, data=some_message, <other options>)

# work with the response:

response.status_code -- the status code

response.content -- the raw content

response.json() -- for services returning JSON, create a Python list or dictionary from the response message.

Let’s explore the github API using the requests library in a Jupyter notebook. Along the way, let’s be sure to write code snippets in the notebook to:

1. retrieve a list of github users.
2. retrieve details about a particular user.
3. get the list of followers for a particular user
4. given two github accounts, determine which account was:
   4a. created first
   4b. updated most recently
   4c. determine if they have any common "starred" repositories