Skip to main content

Introduction into APIs

API stands for 'application programming interface'. Its just a fancy way to talk about connecting two computers. An API allows two programs to interact with each other - including (but not limited to) through the internet.

The middleware of an application is the API that connects the frontend and the backend

APIs allow programs instead of people to make requests to a server and receive a response that code can interpret. Most of the time this response comes in the form of what is called JSON (Javascript Object Notation)

The easiest way to learn what an API is - is to show you. So, open up your terminal (or command prompt) and type this in:

curl https://official-joke-api.appspot.com/random_joke

You should see an output like this (except its a different joke)

{
"id": 421,
"type": "general",
"setup": "Why couldn't the bicycle stand up by itself?",
"punchline": "It was two-tired."
}

If you know python this looks similar to a dictionary. JSON is basically a combination of python lists and dictionaries.

So - to recap - we called a program through a URL that then outputted JSON data. Think of it like asking the server to run a specific function. Just like a function, we have inputs (in this case no inputs), and outputs (the JSON data)

We can call this API in python using the requests package.

import requests

URL = "https://official-joke-api.appspot.com/random_joke"

def get_data(url):
response = requests.get(url)
return response.json()

joke_data = get_data(URL)

print(
f'{joke_data["setup"]}\n...{joke_data["punchline"]}'
)

and we can interpret the results in a stdout

What did the shy pebble wish for?
...That she was a little boulder.

So, what have we done?

tip

We have connected two programmes: our python application and the program that runs on the server outputting a random joke. The output of the server interacts with our program. We have used an API

APIs come in all shapes and sizes - but in the end - an API is just a way for two programs to communicate. We will specifically be looking at Web APIs - APIs that connect through the internet.

Much like most things on the internet - there are certain protocols for Web APIs and data transfer. Most Web APIs are what is called 'RESTful' (Representational State Transfer). I will go into detail a little bit more in later lessons.