Favorites
Hand-picked shortlists of pages grouped by task. Each list links to pages elsewhere on the site, ordered roughly by what to read first.
API scripting
For scripts that call an HTTP API (GET/POST, status codes), parse and build JSON, clean, filter, map and reshape records, then post updates back, all in clear, well-structured code that's easy to adapt when requirements change. Clarity and organization matter more than algorithmic optimization.
HTTP & JSON
- Structuring an API script: the layout and a full worked example. Start here.
- requests: GET/POST, params,
json=, headers, timeouts, errors,Session. - urllib.request: stdlib fallback if
requestsisn't installed. - HTTP status codes: what each code means and how to react.
- json:
loads/dumps, pretty-printing,default=for dates and dataclasses. - Accessing nested JSON:
.getchains, thenulltrap,matchon payloads. - Cleaning & transforming data: filter, normalize, coerce, dedupe, group, join, diff.
- Pagination, retries & batching: generators, backoff,
batched, thread pools. - Secure API scripting: secrets, TLS, injection, SSRF, redirects, HMAC, safe writes.
- Mock API server: a local fake API to practice against, plus
unittest.mock.
Reshaping data
- dict:
get,setdefault,|merge, views, comprehensions. - list: slicing,
append/extend, sorting in place. - str:
strip,split/join,lower/casefold,replace. - String formatting: f-strings for log lines and URLs.
- Comprehensions: list, dict and set comprehensions for filter + map.
- Unpacking:
**dict merging,*rest, tuple unpacking in loops. - sorted and sort: multi-key sorts with
key=andreverse=. - map and filter
- any and all: validation checks across records.
- Conversions:
int,float,str,boolcoercion. - defaultdict: group records by key.
- Counter: count by status or category,
most_common. - groupby: group consecutive records (sort first).
- pairwise and batched: chunk updates for bulk POSTs.
- reduce
Clean, structured scripts
- Functions: keyword-only args, defaults,
*args/**kwargs. - Exceptions:
try/except/else/finally,raise ... from. - match statement: branch on status codes and payload shapes.
- Dataclasses: typed records with
from_api/to_payload. - Type hints:
list[dict],X | None,TypedDict. - Custom exceptions: an
ApiErrorcarrying the status code. - Classes and objects: a small API client class.
- Unit testing: testing pure transform functions.
Extras worth a skim
- Iterators and generators: lazy pagination with
yield. - Decorators: a
@retrywrapper. - Context managers:
with requests.Session(), files. - concurrent.futures: parallel GETs with
ThreadPoolExecutor. - datetime and time: ISO timestamps,
fromisoformat,time.sleepfor backoff. - partial: pre-bind arguments (base URL, headers).
Checklist
- Pin down the task and the payload shapes; check auth, pagination and rate limits.
- Make one request first and print it: status code, then
json.dumps(r.json(), indent=2). - Check
import requestsworks; if not, switch tourllib.requestwith a small helper. - Keep fetch, transform and post in separate functions; constants at the top; a
main(). - Always pass
timeout=; check the status before calling.json(); handle 204 (no body). - Use
.get()for optional fields andd.get("x") or {}for nullable nested objects. - POST one record and check the response before looping over all of them.
- Don't let one bad record crash the run: log it, count failures, keep going.
- Think about retries, idempotency, batching and parallelism, even if you don't build them yet.
Security habits
- Token from
os.environ, sent in a header, never printed or logged; fail fast if it's missing. - HTTPS with verification on; timeouts, retry caps, page caps and response-size caps.
- Validate every response field (type, shape, allowlisted values) before using it.
- Build URLs with
params=andquote(..., safe=""); log untrusted values with%r. - No auth on redirects to other hosts (
allow_redirects=False); allowlist hosts for URLs from data. - POST only allowlisted fields; dry run by default with an
--applyflag and a change limit.