json
json converts between JSON text and Python objects JSON object keys are always strings, so {1 "a"}.
requests
requests is the de facto HTTP client for Python scripts. It's third-party (pip install requests), but most coding platforms preinstall it; if import requests fails, fall back to the stdlib urllib.request. One call does a request always pass timeout=, check the status before parsing, and use a Session when you hit the same API many times (it reuses connections and shared headers). Snippets below run against the local mock API server.
urllib.request
The stdlib HTTP client, for when requests isn't installed. It's more verbose urlopen raises HTTPError for 4xx/5xx instead of returning a response, and a Request with data= defaults to POST. Write a small http_json helper once at the start and the rest of the script looks just like requests code. urllib.parse builds query strings and URLs. Snippets run against the local mock API server.
HTTP status codes
Every HTTP response has a 3-digit status code parse on 2xx, skip or log on 404, stop on 401/403, retry with backoff on 429 and 5xx.
Accessing nested JSON
A parsed response is just nested dicts and lists, but real payloads are messy .get("address", {}) still returns None if the key exists with value null, so use d.get("address") or {}. Before writing any transform, print one record (json.dumps(rec, indent=2)) to see the real shape. Examples use this payload, shaped like the [mock API's /users response:
Cleaning & transforming data
The core of most API scripts: take a list of messy dicts from a GET, then filter (keep what matters), clean (normalize strings, coerce types, fill defaults), map (rename and reshape fields into the target schema), aggregate (group, count, sum, join with another endpoint) and build the payload to POST. Write each step as a small pure function (dict -> dict or list -> list) so it's easy to test and easy to change when the requirements change. Almost everything here is O(n) with comprehensions, dict indexing and defaultdict; sorting is O(n log n). Examples use records shaped like the mock API's users and orders.
Pagination, retries & batching
Real APIs return data a page at a time, fail now and then, and rate-limit you. Pagination retry only transient failures (connection errors, 429, 5xx) with exponential backoff, a cap on attempts, and respect for the Retry-After header; never blindly retry a 4xx. Batching: send updates in chunks with itertools.batched (3.12+) if the API takes bulk payloads, and run independent GETs in parallel with a thread pool. Snippets run against the local mock API server.
Structuring an API script
Clarity and adaptability matter more than cleverness, so give the script a shape that's easy to follow fetch → transform → post → report. When a requirement changes ("also skip users with no email", "send in batches of 10"), you change one function. Work incrementally: make one GET and print a record before writing any transform. The worked example runs against the local mock API server.
Secure API scripting
Even a 100-line script that GETs, transforms and POSTs is part of an attack surface secrets come from the environment and never reach logs, TLS verification stays on, every request has a timeout and a size cap, responses are validated as untrusted input, URLs are built with params=/quote (never string concatenation), auth never follows a redirect or next link to another host, outbound payloads are built from an allowlist of fields, webhook signatures are checked with hmac.compare_digest, and writes default to a dry run. Each is one or two lines. Snippets run against the local mock API server.
Mock API server
To practice without internet or a real API, run this stdlib-only fake JSON API on http8000. It's built on http.server plus a match router, and every snippet in this section runs against it. It has page-number pagination (/users), cursor pagination (/orders), a POST endpoint that validates its body (/users//summary), a bearer-token endpoint (/me), a flaky endpoint for retry logic, /status/{code} for any status, /echo, which reflects your request back, and /redirect, an open redirect for the security demos. The data is deliberately messy (padded names, mixed-case status, null fields, string amounts) so the cleaning code has something to fix. Restart the server to reset its state (POST ids, the flaky counter). For unit tests, skip the server and patch requests with unittest.mock instead.
Flask
Flask is a small third-party web framework (pip install flask) for building HTTP APIs. You create a Flask app, map URLs to view functions with @app.get/@app.post, read input from request (args, getjson(), headers), and return a dict or list, which Flask turns into a JSON response, optionally with a status code and headers. Per-request overhead is small a fake server for the scripts in this section, a webhook receiver, or a small internal service. Gotchas deploy behind a WSGI server like Gunicorn.
FastAPI
FastAPI is a third-party web framework (pip install "fastapistandard]") for JSON APIs, built on Starlette and Pydantic. Type hints do the work bad input is 422, not 400; the default status is 200 even for a POST (set status_code=201); errors come back as {"detail": ...}; routes match in order, so declare /users/me before /users/; and never call blocking code (requests, time.sleep) inside an async def endpoint.