Skip to content

16. APIs and web data — Cheat sheet

The essentials of module 16 on one page. Every runnable block on this page is checked against its output; network code is shown but not run.

I want to… Use… Example
send one GET request httpx.get() / requests.get() httpx.get(url, params={"page": 1}, timeout=10)
reuse settings and connections a client httpx.Client(base_url=..., headers=..., timeout=10.0)
add query parameters params= client.get("/products", params={"page": 2})
send a JSON body json= client.post("/orders", json={"id": "P001", "qty": 2})
fail on any status that is not 2xx raise_for_status() client.get(url).raise_for_status().json()
parse a JSON body response.json() page = response.json()
read a header response.headers[...] (case-insensitive) response.headers["retry-after"]
see the URL that was sent response.url / response.request print(response.request.url)
set a timeout timeout= httpx.Timeout(10.0, connect=3.0)
follow redirects in httpx follow_redirects=True httpx.Client(follow_redirects=True)
test without a network httpx.MockTransport(handler) httpx.Client(transport=httpx.MockTransport(fake))
count or log every request event hooks httpx.Client(event_hooks={"request": [log]})
collect all pages follow next with a page limit for _ in range(max_pages): ...
retry transient failures 429, 5xx, httpx.TransportError backoff min(cap, base * 2 ** (k - 1))
honor a rate limit Retry-After header float(response.headers["Retry-After"])
test waits without waiting inject sleep get_with_retry(..., sleep=waits.append)
read an API key os.environ.get() os.environ.get("MAPLE_API_KEY")
load a .env file python-dotenv load_dotenv()
send a bearer token Authorization header headers={"Authorization": f"Bearer {key}"}
take a URL apart urllib.parse.urlsplit(), parse_qs() parse_qs(urlsplit(url).query)
parse HTML BeautifulSoup(html, "html.parser") soup.select("tbody tr")
read an attribute tag["attr"] / tag.get("attr") row["data-id"]
read text tag.get_text(strip=True) td.get_text(strip=True)
flatten nested JSON recursive flatten() or pd.json_normalize() pd.json_normalize(items, sep="_")
fetch pages concurrently httpx.AsyncClient + asyncio.gather() limit with asyncio.Semaphore(n)
Method Does Body Safe Idempotent Retry on failure
GET read no yes yes yes
HEAD read headers only no yes yes yes
POST create, run an action yes no no only with an idempotency key
PUT replace yes no yes yes
PATCH change part yes no no with care
DELETE remove no no yes yes
Code Phrase Meaning Client action
200 OK success read the body
201 Created resource created read the new resource or its Location
204 No Content success, empty body do not call .json()
301 / 302 Moved Permanently / Found redirect follow Location
304 Not Modified your cached copy is current use the cache
400 Bad Request malformed request fix the request
401 Unauthorized missing or invalid credentials check the key
403 Forbidden valid credentials, no permission check the key’s scope
404 Not Found no such resource fix the URL, or treat as “no data”
409 Conflict clashes with the current state reload and decide
422 Unprocessable Content valid JSON, invalid field fix the data
429 Too Many Requests rate limit hit wait Retry-After, then retry
500 Internal Server Error server bug retry with backoff
502 / 504 Bad Gateway / Gateway Timeout proxy problem retry with backoff
503 Service Unavailable overloaded or in maintenance retry with backoff
Header Sent by Example
Accept client application/json
Content-Type both application/json, text/html; charset=utf-8
Authorization client Bearer mf_live_...
User-Agent client maple-analytics/1.0 (data-team@example.org)
If-None-Match client the ETag of your cached copy
ETag server "v42": a version tag of the resource
Retry-After server 30 or Wed, 01 May 2024 12:01:00 GMT
X-RateLimit-Limit / -Remaining / -Reset server 60 / 0 / 1714564860 (a common convention)
Link server <https://...?page=3>; rel="next"
from urllib.parse import parse_qs, urlencode, urlsplit
url = "https://api.example.com/v1/products?page=2&per_page=10"
parts = urlsplit(url) # scheme, netloc, path, query, fragment
print(parts.netloc, parts.path, parse_qs(parts.query)) # values are lists of str
print(urlencode({"q": "rain jacket", "tag": ["new", "sale"]}, doseq=True)) # encode
Output
api.example.com /v1/products {'page': ['2'], 'per_page': ['10']}
q=rain+jacket&tag=new&tag=sale
Task httpx requests
install httpx requests
one call httpx.get(url, params=p, timeout=10) requests.get(url, params=p, timeout=10)
client httpx.Client(base_url=..., headers=...) requests.Session(); session.headers.update(...)
base URL base_url= none: build full URLs
default timeout 5 s none (waits forever)
redirects off; follow_redirects=True on
JSON body json=data json=data
form body data={...} data={...}
status error httpx.HTTPStatusError requests.HTTPError
timeout error httpx.TimeoutException requests.Timeout
connection error httpx.ConnectError requests.ConnectionError
base exception httpx.HTTPError requests.RequestException
params= with a URL that has a query replaces the whole query appends to it
async httpx.AsyncClient no
test double httpx.MockTransport responses package
built-in retries httpx.HTTPTransport(retries=3) (connection errors only) HTTPAdapter(max_retries=urllib3.Retry(...))
client.py
import os
import httpx
client = httpx.Client(
base_url="https://api.example.com/v1",
headers={
"Accept": "application/json",
"User-Agent": "maple-analytics/1.0 (data-team@example.org)",
"Authorization": f"Bearer {os.environ['MAPLE_API_KEY']}",
},
timeout=httpx.Timeout(10.0, connect=3.0), # connect, then read/write/pool
)
with client:
page = client.get("/products", params={"page": 1}).raise_for_status().json()
created = client.post("/orders", json={"product_id": "P001", "quantity": 2})
import httpx
def fake_api(request: httpx.Request) -> httpx.Response:
"""Answer like the real API; the client code stays unchanged."""
if request.url.path == "/v1/products":
page = int(request.url.params.get("page", "1"))
return httpx.Response(200, json={"page": page, "data": [], "next": None})
return httpx.Response(404, json={"error": "not_found"})
client = httpx.Client(
base_url="https://api.example.com/v1", transport=httpx.MockTransport(fake_api)
)
response = client.get("/products", params={"page": 2})
print(response.status_code, response.json(), response.request.url)
print(client.get("/nope").status_code)
Output
200 {'page': 2, 'data': [], 'next': None} https://api.example.com/v1/products?page=2
404
Fake How
a saved body httpx.Response(200, content=Path("page.json").read_bytes(), headers={"Content-Type": "application/json"})
an error status httpx.Response(503)
a rate limit httpx.Response(429, json=body, headers={"Retry-After": "30"})
a timeout raise httpx.ReadTimeout("timed out", request=request)
a refused connection raise httpx.ConnectError("refused", request=request)
flaky, then fine a closure with a list of statuses to pop first
an async server async def handler(request) with httpx.AsyncClient
httpx exception tree
HTTPError
├── HTTPStatusError raise_for_status() on non-2xx (has .request and .response)
└── RequestError no usable response
└── TransportError
├── TimeoutException ConnectTimeout, ReadTimeout, WriteTimeout, PoolTimeout
├── NetworkError ConnectError, ReadError, WriteError, CloseError
└── ProtocolError, ProxyError, UnsupportedProtocol
response = client.get("/nope")
try:
response.raise_for_status()
except httpx.HTTPStatusError as exc:
print(type(exc).__name__, exc.response.status_code, exc.response.json())
Output
HTTPStatusError 404 {'error': 'not_found'}
Style First request Next request Stop when
page number ?page=1&per_page=100 page + 1 page == total_pages or empty data
offset/limit ?offset=0&limit=100 offset + limit fewer than limit items
cursor no cursor ?cursor=<next_cursor> next_cursor is null
next link (body) first URL page["next"] next is null
next link (header) first URL response.links["next"]["url"] no next link
pagination.py
def iter_items(client, path, max_pages=100):
url, params = path, {"page": 1, "per_page": 100}
for _ in range(max_pages): # safety stop
page = client.get(url, params=params).raise_for_status().json()
yield from page["data"]
url, params = page["next"], None # httpx: params would replace the query
if url is None:
return
raise RuntimeError("too many pages")
Rule Why
Retry 429, 500, 502, 503, 504 and transport errors they are transient
Never retry other 4xx the same request fails the same way
Wait Retry-After when present earlier retries earn more 429s
Backoff dk=min⁡(dmax⁡,b⋅2k−1)d_k = \min(d_{\max}, b \cdot 2^{k-1}) gives the server time to recover
Add jitter: random.uniform(0, d_k) spreads out clients that failed together
Cap the attempts (3–5) and let the last error propagate a pipeline must fail loudly
Retry only idempotent requests a retried POST can create duplicates
Inject sleep (and the clock) tests run instantly and exactly
Throttle to 60 / limit_per_minute seconds between requests avoid 429s up front
import time
from collections.abc import Callable
RETRY = frozenset({429, 500, 502, 503, 504})
def get_with_retry(
client: httpx.Client,
url: str,
attempts: int = 4,
sleep: Callable[[float], None] = time.sleep,
) -> httpx.Response:
for k in range(1, attempts):
try:
response = client.get(url)
except httpx.TransportError:
wait = min(30.0, 2.0 ** (k - 1)) # no response: backoff
else:
if response.status_code not in RETRY:
return response.raise_for_status() # success, or a 4xx to fix
value = response.headers.get("Retry-After", "")
wait = float(value) if value.isdigit() else 2.0 ** (k - 1) # seconds form
sleep(wait)
return client.get(url).raise_for_status() # last attempt: errors propagate
statuses = [429, 503, 200]
def flaky(request: httpx.Request) -> httpx.Response:
status = statuses.pop(0)
headers = {"Retry-After": "30"} if status == 429 else {}
return httpx.Response(status, headers=headers)
waits: list[float] = []
flaky_client = httpx.Client(transport=httpx.MockTransport(flaky))
print(get_with_retry(flaky_client, "https://api.example.com/v1/x", sleep=waits.append))
print(waits)
Output
<Response [200 OK]>
[30.0, 2.0]
Do Do not
os.environ.get("MAPLE_API_KEY") and fail clearly if it is missing write the key in the code or a notebook
keep local keys in .env, listed in .gitignore commit .env
commit .env.example with empty values share keys in chat or screenshots
send keys in the Authorization header put keys in the URL query (they end up in server logs)
one client per base URL; the key only on the API client reuse an authenticated client for another host: its headers go along
mask keys in output: "*" * 8 + key[-4:] print(key) or put the key in an error message
revoke a leaked key at once only delete the commit
Terminal (macOS, Linux)
export MAPLE_API_KEY="mf_live_..." # this terminal only
uv pip install python-dotenv # optional: load a .env file
Terminal (Windows PowerShell)
$env:MAPLE_API_KEY = "mf_live_..." # this terminal only
settings.py
from dotenv import load_dotenv # pip/uv package: python-dotenv
load_dotenv() # .env lines NAME=value -> os.environ; existing variables win
Need Code
parse soup = BeautifulSoup(html, "html.parser")
all matches by CSS soup.select("table#products tbody tr")
first match or None soup.select_one("span.price")
by tag and attributes soup.find_all("a", href=True), soup.find("a", rel="next")
by class without CSS soup.find_all("article", class_="product-card")
attribute (must exist) tag["data-id"]
attribute (may be missing) tag.get("data-id")
all attributes tag.attrs (a dict)
text, trimmed tag.get_text(strip=True)
text with a separator tag.get_text(" ", strip=True)
children / parent tag.find_all(recursive=False), tag.parent
multi-valued attributes class and rel are lists: "in" in tag["class"]
CSS selector Matches
p every <p>
.price / #products class price / id products
span.price-old <span> with class price-old
p.stock.out <p> with both classes
tbody tr <tr> anywhere inside <tbody>
h2 > a <a> directly inside <h2>
[data-rating] / a[rel="next"] has the attribute / attribute equals
a[href^="/products/"] attribute starts with
tr:nth-of-type(2) the second <tr> among its siblings
from bs4 import BeautifulSoup
html = """<table id="t"><tr><th>ID</th><th>Price</th></tr>
<tr data-id="P001"><td>P001</td><td class="price">$1,299.00</td></tr></table>"""
soup = BeautifulSoup(html, "html.parser")
headers = [th.get_text(strip=True).lower() for th in soup.select("th")]
rows = []
for tr in soup.select("tr[data-id]"):
cells = [td.get_text(strip=True) for td in tr.find_all("td")]
rows.append(dict(zip(headers, cells, strict=True)))
rows[0]["price"] = float(rows[0]["price"].lstrip("$").replace(",", ""))
print(rows)
Output
[{'id': 'P001', 'price': 1299.0}]

Scraping etiquette: check the terms and robots.txt, send a descriptive User-Agent, stay under one request per second, cache pages and prefer an API when one exists.

JSON Python
object dict
array list
string str (dates stay strings)
number int or float
true / false True / False
null None
from typing import Any
def flatten(record: dict[str, Any], prefix: str = "") -> dict[str, Any]:
flat: dict[str, Any] = {}
for key, value in record.items():
if isinstance(value, dict):
flat.update(flatten(value, f"{prefix}{key}_"))
else:
flat[f"{prefix}{key}"] = value
return flat
item = {"id": "P001", "price": {"amount": 79.99, "currency": "USD"}, "tags": ["new"]}
print(flatten(item)) # lists stay lists: join them or explode them into rows
Output
{'id': 'P001', 'price_amount': 79.99, 'price_currency': 'USD', 'tags': ['new']}
Tool Use
pd.json_normalize(items, sep="_") nested dicts to columns
pd.json_normalize(customers, record_path="orders", meta=["customer_id"]) one row per nested record, here per order
df.explode("tags") one row per list element, after loading
csv.DictWriter(f, fieldnames=cols) tidy records to CSV without pandas
  • requests has no default timeout: a dead server hangs your script forever. Always pass timeout=.
  • httpx does not follow redirects by default, and raise_for_status() raises for a 301 or 302. Pass follow_redirects=True when you expect them.
  • httpx replaces the whole query string of a URL when you pass params, even params={}. With a next link, pass params=None. Client-level params= has the same effect on every request.
  • response.json without () is the method, not the data: TypeError: 'method' object is not subscriptable.
  • raise_for_status() returns the response in httpx, so client.get(url).raise_for_status().json() chains. In requests it returns None; call it on its own line.
  • A 204 No Content has no body: response.json() raises JSONDecodeError.
  • A proxy can answer 200 with an HTML error page. Check Content-Type before .json().
  • Header names are case-insensitive in both libraries; plain dicts of headers that you build yourself are not.
  • parse_qs() returns lists of strings. Query values are always text: convert them.
  • A pagination loop needs a hard page limit, and a check that len(items) == total with unique ids.
  • Retry-After can be a date instead of seconds. email.utils.parsedate_to_datetime() parses it.
  • Retrying a ReadTimeout on a POST can duplicate the action: the server may have done it already.
  • time.sleep() in tests makes them slow. Inject sleep and record the waits.
  • httpx masks Authorization as [secure] when it prints headers. Your own f-strings do not.
  • In BeautifulSoup, class and rel are lists. tag["class"] == "price" is always False.
  • select_one() and find() return None when nothing matches. Check before .get_text().
  • "html.parser" is built in. "lxml" is faster but needs an extra package; both give the same tree for clean HTML.
  • Price text such as $1,299.00 needs cleaning before float(). $ and , are display formatting.