Skip to main content

APIs & JSON scripting

HTTP requests, JSON, cleaning and reshaping data, structuring API scripts, and small Flask and FastAPI servers.

📄️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.

📄️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.