What an API is and how data is exchanged (JSON)
An API (Application Programming Interface) is an agreement on how one program asks another for data or services. On the web it is a set of addresses on a server that return data instead of HTML pages, most often in the JSON format. Mobile apps, weather forecasts, maps and payments all work through APIs.
How to learn: try every example in the browser or on the command line and do the exercises from the lesson. The examples are in HTML, JavaScript and Python; for most of them a browser is enough, and for the Python examples you need Python 3 installed.
An API: the waiter between frontend and backend
In a restaurant you do not go into the kitchen – you give your order to the waiter according to the menu. An API is such a menu: it says which addresses exist, what is sent to them and what they return.
| Request | Meaning | Response |
|---|---|---|
GET /api/tasks | give me all tasks | a list of tasks (JSON) |
GET /api/tasks/17 | give me task number 17 | one task or 404 |
POST /api/tasks | create a new task (data in the body) | 201 Created + the new task |
PUT /api/tasks/17 | change task 17 | 200 OK |
DELETE /api/tasks/17 | delete task 17 | 204 No Content |
This style – addresses are "things" (resources), and HTTP methods are "actions" – is called REST. In this way the same backend serves both the website and the mobile app.
JSON: a data format
JSON (JavaScript Object Notation) is a text notation for data that both people and programs read easily:
{
"name": "Ana",
"grade": 7,
"competitor": true,
"results": [100, 85, 92],
"school": { "name": "Vuk Karadžić Primary School", "city": "Pančevo" }
}
| Element | Notation | In Python | In JavaScript |
|---|---|---|---|
| object | { "key": value } | dictionary (dict) | object |
| array | [1, 2, 3] | list | array (Array) |
| text | "Ana" (double quotes are required) | str | string |
| number, boolean, empty | 7, true, null | int/float, True, None | number, true, null |
Calling an API from JavaScript
In the browser an API is called with the fetch function. The example uses the free weather forecast API Open-Meteo (no registration):
<p>Temperature in Pančevo: <span id="temp">…</span> °C</p>
<script>
const url = "https://api.open-meteo.com/v1/forecast?latitude=44.87&longitude=20.64¤t=temperature_2m";
fetch(url) // send a GET request
.then(response => response.json()) // turn the JSON text into an object
.then(data => {
document.getElementById("temp").textContent = data.current.temperature_2m;
})
.catch(error => console.log("Error:", error)); // e.g. no internet
</script>
Open F12 → Network → the Fetch/XHR filter: you will see the request to the API and the JSON response in the Response tab.
Calling an API from Python
In Python, JSON is turned into a dictionary with the json module, and requests are most often sent with the requests library:
import json
text = '{"name": "Ana", "grade": 7, "results": [100, 85, 92]}'
student = json.loads(text) # JSON text -> dictionary
print(student["name"], student["grade"])
print("average:", sum(student["results"]) / len(student["results"]))
student["grade"] = 8
print(json.dumps(student, ensure_ascii=False)) # dictionary -> JSON text
Ana 7
average: 92.33333333333333
{"name": "Ana", "grade": 8, "results": [100, 85, 92]}
import requests # installation: pip install requests
url = "https://api.open-meteo.com/v1/forecast"
parameters = {"latitude": 44.87, "longitude": 20.64, "current": "temperature_2m"}
response = requests.get(url, params=parameters, timeout=10)
print(response.status_code) # 200 if everything is fine
data = response.json() # JSON -> dictionary
print(data["current"]["temperature_2m"], "°C")
API keys and limits
- Many APIs require a key (API key) – a secret string of characters by which they know who is calling them. The key is not published in the code on GitHub and is not put into the frontend.
- There are limits (e.g. 1000 requests a day); after that the server returns
429 Too Many Requests. - The browser does not let a page from one domain freely read data from another, unless that server explicitly allows it (the CORS rule). That is why some APIs work from Python but not from the browser.
- In JSON, keys and text must be in double quotes, and the last element must not have a comma after it.
- Always check the status of the response (200, 404, 429…) before reading the data.
- An API key is like a password – do not share it and do not put it into JavaScript on the page.
Check your knowledge
Open the quiz
API and JSON
1. What does a typical web API return?
2. Which method in a REST API creates a new record?
3. Which Python function turns JSON text into a dictionary?
