How an API call works
π€Request
GET /orders?page=1 + Authorization header
π₯οΈServer
Checks the token, finds the data
π₯Response
Status code + headers + JSON body
| Status | Meaning | What your code does |
|---|---|---|
| 200 OK | Success | Use the data |
| 400 Bad Request | Your parameters are wrong | Fix the code; don't retry |
| 401 / 403 | Missing/wrong token, or no permission | Fix credentials; don't retry |
| 404 Not Found | Wrong URL or id | Don't retry |
| 429 Too Many Requests | Rate limited | Wait, then retry |
| 500 / 502 / 503 / 504 | Server problem | Retry with backoff |
Your first request
import os
import requests
BASE_URL = "http://localhost:8765"
headers = {"Authorization": f"Bearer {os.environ['SHOPKART_API_TOKEN']}"} # secret from an env var
response = requests.get(f"{BASE_URL}/orders", params={"page": 1}, headers=headers, timeout=10)
print(response.status_code)
print(response.headers["Content-Type"])
print(response.json())200
application/json
{'page': 1, 'next_page': 2, 'items': [{'order_id': 101, 'amount': 1999, 'status': 'DELIVERED'}, {'order_id': 102, 'amount': 4999, 'status': 'DELIVERED'}]}paramsbuilds the query string (?page=1) safely.headerscarries the token, read from an environment variable, never typed into code.timeout=10: give up after 10 seconds instead of hanging forever.
r = requests.get(f"{BASE_URL}/orders", timeout=10) # forgot the token
print(r.status_code, r.json())401 {'error': 'missing or wrong token'}r = requests.get(f"{BASE_URL}/payments", headers=headers, timeout=10)
r.raise_for_status() # turns 4xx/5xx into an exceptionHTTPError: 404 Client Error: Not Found for url: http://localhost:8765/paymentsPagination: get every page
def fetch_all_orders() -> list[dict]:
orders, page = [], 1
while page is not None: # keep going until there's no next page
r = requests.get(f"{BASE_URL}/orders", params={"page": page, "page_size": 2},
headers=headers, timeout=10)
r.raise_for_status()
body = r.json()
orders.extend(body["items"])
print(f"page {body['page']}: {len(body['items'])} orders")
page = body["next_page"]
return orders
orders = fetch_all_orders()
print(f"total: {len(orders)} orders")page 1: 2 orders page 2: 2 orders page 3: 1 orders total: 5 orders
| Pagination style | How you move on |
|---|---|
| Page number | page=1, 2, 3 β¦ until next_page is null (our API) |
| Offset / limit | offset=0, 100, 200 β¦ until fewer than limit come back |
| Cursor | Send the cursor/token from the last response (most robust for changing data) |
| Link header / next URL | Follow the URL the response gives you |
Automatic retries
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retry = Retry(total=5, backoff_factor=0.1, status_forcelist=[429, 500, 502, 503, 504])
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))
session.headers.update(headers)
r = session.get(f"{BASE_URL}/flaky", timeout=10) # fails twice with 503, then succeeds
print(r.status_code, r.json())200 {'ok': True, 'attempts': 3}The /flaky endpoint failed twice with 503; the session retried with growing waits and the third attempt succeeded. A Session also reuses connections (faster) and shares headers across calls.
Save the raw response (bronze)
import json
from datetime import date
from pathlib import Path
out = Path("bronze") / f"orders_{date(2026, 4, 1).isoformat()}.jsonl"
out.parent.mkdir(exist_ok=True)
with out.open("w", encoding="utf-8") as f:
for o in orders:
f.write(json.dumps(o) + "\n") # raw, one JSON per line (bronze)
print(out, out.stat().st_size, "bytes")
print(out.read_text().splitlines()[0])bronze/orders_2026-04-01.jsonl 285 bytes
{"order_id": 101, "amount": 1999, "status": "DELIVERED"}Saving exactly what the API returned, before any cleaning, means you can re-run transformations later without calling the API again, and debug βwhat did the API actually send?β. One file per day, JSON Lines.
Being a good API citizen
- Respect rate limits; read the
Retry-Afterheader on 429. - Fetch incrementally: ask only for records changed since your last run (
updated_since=), like a watermark. - Log the URL, status and row count of each call (never the token).
- Use a cursor if the data changes while you page through it, or you may skip or repeat records.
π― Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1GET vs POST?Fresher+
Q2How do you extract all records from a paginated API reliably?1β3 yrs+
Q3How do you handle API rate limits?1β3 yrs+
Q4How do you keep API credentials secure in a pipeline?1β3 yrs+
Q5How would you speed up pulling 10,000 API pages?3+ yrs+
Key takeaways
- βAPIs are a main source of pipeline data: request, check status, parse JSON.
- βPagination and retries are where real extraction code earns its keep.
- βSecrets live in environment variables; raw responses go to bronze.
- βNext: pandas, the workhorse for cleaning tables in Python.
Frequently asked questions
What is a REST API?
A way for programs to exchange data over HTTP. You send a request to a URL (like GET /orders?page=1) and get a response with a status code and usually JSON data.
Why always set a timeout?
Without one, requests can wait forever if the server never answers, and your pipeline hangs silently. Set timeout=10 (seconds) or similar on every call.
How should I store API keys?
In environment variables or a secrets manager (Databricks secrets, AWS Secrets Manager, Azure Key Vault), never in code or Git. Read them with os.environ.
What is pagination?
APIs return big results in pages. You request page 1, then follow the 'next page' info (a number, a cursor or a URL) until there are no more pages.
What does HTTP 429 mean?
Too Many Requests: you hit the rate limit. Wait (check the Retry-After header) and retry with backoff.
π§ Quick check: APIs with requests
1. Status code 200 means...
2. r.raise_for_status() does what on a 404?
3. Which errors are worth retrying?
4. Where do raw API responses go in a medallion design?
Checking your accessβ¦