Getting and cleaning data · lesson 4 of 11
Parts in this lesson
Arequests.get(url, params=..., timeout=10)ask an API for data
Bpd.json_normalize(results)nested JSON into columns
Cos.environ["TINDAHAN_API_KEY"]a secret from outside the code

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=1

and 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).

codemeanswhat to do
200OKread the data
401 or 403no key, or a key without permissioncheck the key
404no such addresscheck the URL
429too many requestswait, then slow down
500 to 599the server failedtry 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.

Nested JSON unfolding into columns. One result from the price list. A table wants one value per cell, but price is a dictionary inside it, and stock is a list.{ "item": "rice", "unit": "kg", "price": { "amount": 46.0, "currency": "PHP" }, "stock": [ {"store": "Batangas", "in_stock": true}, {"store": "Lipa", "in_stock": true} ]}one result
1 of 3 One result from the price list. A table wants one value per cell, but price is a dictionary inside it, and stock is a list.
prices.ipynb
  • json.loads turns 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. The price dictionary becomes two columns, price.amount and price.currency. The stock list stays a list in one column, which isn't useful yet.
  • record_path="stock" makes one row per entry in each stock list, and meta copies other fields onto each row. ["price", "amount"] reaches inside price. 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)
  • params builds the ?page=1 part safely; don't paste values into the URL yourself.
  • timeout=10 gives 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't

Then 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:

Windows (PowerShell)
$env:TINDAHAN_API_KEY = "paste-the-key-here"
jupyter lab
macOS or Linux
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:

key.ipynb

If you keep keys in a .env file to save typing, add .env to .gitignore so it's never shared.

Check what you learned

An API answers with status code 429. What does it mean?
Each result has "price": {"amount": 46.0, "currency": "PHP"}. What columns does json_normalize make from it?
Where should an API key live?

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.

All sources for Simple Data Analysis