Web APIs and JSON
Last updated
Many services hand out data through an API: a web address that answers with data instead of a page, usually as JSON. In this lesson you'll flatten nested JSON into a table with json_normalize, combine pages of results, see how requests fetches them on your computer, and keep the key that unlocks an API out of your notebooks.
By the end of this lesson you can
- Say what an API is, and what its status codes mean
- Flatten nested JSON into a DataFrame with
pd.json_normalize - Combine paged results, and save each raw response
- Keep API keys out of notebooks with environment variables
What an API sends
An API (application programming interface) is a web address made for programs. Instead of a page for a person, it answers with data. You ask with a URL and some settings:
https://api.example.com/v1/prices?page=1and it answers with a status code and a body, usually JSON: the same dictionaries and lists as Python, written as text (Simple Python covers the json module).
| code | means | what to do |
|---|---|---|
| 200 | OK | read the data |
| 401 or 403 | no key, or a key without permission | check the key |
| 404 | no such address | check the URL |
| 429 | too many requests | wait, then slow down |
| 500 to 599 | the server failed | try again later |
Most APIs send big answers in pages, say 100 results at a time, with a note saying how many pages there are. Most also ask for a key: a secret string that says who's asking, so they can limit how much each user takes.
This page can't reach the internet, so the API's two pages of answers have been saved in data/raw/, as you should always do anyway.
Flattening JSON
Step through what happens to one result, then run the cells.
price is a dictionary inside it, and stock is a list.json.loadsturns the saved text into Python dictionaries and lists. The page says it's page 1 of 2, with 2 results.pd.json_normalize(page["results"])makes one row per result. Thepricedictionary becomes two columns,price.amountandprice.currency. Thestocklist stays a list in one column, which isn't useful yet.record_path="stock"makes one row per entry in eachstocklist, andmetacopies other fields onto each row.["price", "amount"]reaches insideprice. Now each row is a store and an item: four rows.- Paging: the last cell reads every page into one list, then normalises the lot: three items, with oil from page 2.
To rename the dotted columns, rename(columns={"price.amount": "price"}).
Fetching it on your computer
On your own computer, the requests library fetches the pages (python -m pip install requests). This is the shape of nearly every API download:
import json
import os
import time
from pathlib import Path
import requests
KEY = os.environ["TINDAHAN_API_KEY"]
URL = "https://api.example.com/v1/prices"
rows, page = [], 1
while True:
r = requests.get(URL, params={"page": page},
headers={"Authorization": f"Bearer {KEY}"}, timeout=10)
r.raise_for_status()
Path(f"data/raw/prices_page{page}.json").write_text(r.text, encoding="utf-8")
data = r.json()
rows.extend(data["results"])
if page >= data["pages"]:
break
page += 1
time.sleep(1)paramsbuilds the?page=1part safely; don't paste values into the URL yourself.timeout=10gives up after 10 seconds instead of waiting forever.raise_for_status()turns a 4xx or 5xx code into an error, so a failed request never looks like empty data.- Save every raw response in
data/raw/before using it. The API may change or disappear, and your analysis must be rerunnable from what you saved. time.sleep(1)waits between pages. APIs have rate limits; read the documentation, and stay well under them.
Wrong way: a key in a shared notebook
It's tempting to write the key straight into the notebook:
KEY = "sk_live_8f2a…" # don'tThen the notebook is emailed to a colleague, or pushed to GitHub, or printed into a report. Now anyone with the file can use the key: run up your bill, use up your rate limit, or read data that was meant for you. Bots search public code for keys all day. Deleting the line later doesn't help, because old versions keep it. A leaked key has to be revoked and replaced. Simple Cybersecurity has more on keeping secrets.
Keep keys in an environment variable instead: a setting of the terminal, outside every file. Set it in the terminal before starting JupyterLab:
$env:TINDAHAN_API_KEY = "paste-the-key-here" jupyter lab
export TINDAHAN_API_KEY="paste-the-key-here" jupyter lab
The notebook reads it with os.environ["TINDAHAN_API_KEY"], and the key is never in the file. This page has no such variable, so it prints None:
If you keep keys in a .env file to save typing, add .env to .gitignore so it's never shared.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- pandas: pandas.json_normalize: record_path, meta, and dotted column names
- Requests: Quickstart: get, params, headers, status codes and json()
- MDN: HTTP response status codes: what 200, 401, 404, 429 and 500 mean
- RFC 8259: The JSON Data Interchange Format: the JSON standard
- The Python Standard Library: os.environ: reading environment variables