00.6 HTTP, REST and JSON
Almost everything you will build as an AI engineer talks to the outside world the same way: your code sends an HTTP request and reads back a JSON body. The LLM providers are HTTP APIs. Stripe, GitHub, your own database admin panel and the vector database in a RAG pipeline are HTTP APIs. Even the "API" in "API key" means this: a way for two programs to talk over HTTP. This lesson takes you from "I have used the web" to "I can read any API request and response, predict what a well-designed one looks like, and debug the ones that fail". You will learn the HTTP protocol in depth, the JSON data format completely, the vocabulary of REST API design, how authentication works, and how to call APIs by hand — with curl, in the browser, and in Python.
What you'll learn
- What an HTTP request and response actually contain, byte for byte, and what every method and status code means
- How URLs are built, including percent-encoding and query strings
- The headers that carry authentication, content type, caching, rate limits and tracing — and how to read them
- HTTP versions, keep-alive, compression and why every network call needs a timeout
- JSON completely: the six types, what is forbidden,
json.loads/json.dumpsin Python, JSON Lines,jq, and how JSON compares with YAML, TOML, CSV, XML, Protocol Buffers and MessagePack - JSON Schema, the standard way to describe the shape of JSON — previewed here, used for LLM structured output in 03.4
- REST vocabulary: resources, collections, pagination, filtering, versioning, idempotency keys, consistent error bodies, rate limits and webhooks
- How REST compares with RPC, GraphQL, gRPC, WebSockets and SSE — the streaming format every LLM API uses
- How APIs authenticate you: API keys, bearer tokens, basic auth, OAuth 2.0 and signed requests, including where each LLM provider puts its key
- How to call APIs by hand:
curlrecipes, browser DevTools, API clients, and a standard-library Python client you can run offline against a fake server — plus a decision table for which tool to reach for - A raw LLM API call for each provider — OpenAI, Anthropic, Gemini and OpenRouter — as plain HTTP and JSON, with no SDK
- How to debug HTTP failures: reading status and body together, the common failure table,
-vtraces, request IDs and when to retry
What you don't need
- Any programming experience beyond reading Python — every snippet is explained, and the running examples use only the Python standard library.
- An API key, an account, or internet access for most of the lesson. The worked LLM examples are shown as requests and responses you can read; lesson 03.1 shows how to make them for real.
- Knowledge of web architecture. Lesson 00.5 explains client, server and database; this lesson goes one level deeper into the protocol between them.
Setup
You need a terminal and a text editor (lesson 00.1 sets both up), and Python 3.11 or newer — check with python3 --version. No API key needed. Everything that runs does so on your own machine: JSON handling is pure Python, and the "API" you will call is a tiny fake server running on 127.0.0.1 (your own computer) that the script starts and stops itself. curl is recommended but optional — it ships with macOS and Linux, and Windows 10+ includes it (in PowerShell, write curl.exe; plain curl is a different command there). jq, a command-line JSON tool, is optional and covered where it appears.
What you must be able to do after this lesson#
- Read an HTTP request and response and explain the method and status code
- Build a URL with a query string and percent-encoding
- Write and parse valid JSON in Python
- Explain REST vocabulary such as resources, pagination and idempotency
- Call an API by hand with curl and Python
- Make a raw LLM API call and read the response
- Debug a failing HTTP call step by step
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"It's just an HTTP POST to /v1/responses with a JSON body." |
1.2 Anatomy of a request |
"We got a 429 — back off and retry." |
1.5 Status codes and 3.8 Rate limits |
"Put the key in the Authorization header, never the URL." |
Part 4: Authentication |
| "The API paginates with an opaque cursor." | 3.3 Pagination |
| "Send an idempotency key so a retry can't double-charge." | 3.6 Idempotency keys |
"The model streams back text/event-stream." |
3.10 REST vs the alternatives |
| "The batch file is JSONL — one request per line." | 2.6 JSON Lines |
"That field is null in the response, not missing." |
2.3 json.loads and json.dumps |
"The docs say application/problem+json for errors." |
3.7 Errors |
| "Our client needs connect and read timeouts." | 1.8–1.9 Versions and timeouts |
| "The webhook signature didn't verify — check the raw body." | 3.11 Webhooks |
"Python wrote NaN into our JSON and the API rejected it." |
2.2 What JSON is not |
Part 1: HTTP — the protocol of the web#
1.1 What HTTP is#
HTTP (HyperText Transfer Protocol) is the application-level protocol of the web, defined by the IETF in RFC 9110 (HTTP Semantics) and its companions — RFC 9112 for HTTP/1.1, RFC 9113 for HTTP/2 and RFC 9114 for HTTP/3, all as of November 2026. Three properties matter for everything in this lesson:
- It is a request/response protocol. One side (the client) sends a request; the other (the server) sends back exactly one response, then the exchange is over — unless the response is a stream that stays open (SSE, covered in 3.10).
- It is stateless. The server remembers nothing between requests. Every request must carry everything the server needs — which is why APIs resend your API key on every call, and why "sessions" have to be rebuilt from cookies or tokens each time (lesson 00.5 covers this idea; here you see the wire-level consequence).
- It is plain text. A request and a response are sequences of readable characters: a start line, headers, a blank line, then an optional body. You can type one by hand — 1.10 does exactly that.
1.2 Anatomy of a request and a response#
Here is a complete HTTP request, exactly as it travels over the network (the \r\n are carriage-return + line-feed, the line endings HTTP mandates):
POST /v1/tickets?priority=high HTTP/1.1
Host: tickets.example.com
Authorization: Bearer sk-demo-...
Content-Type: application/json
Content-Length: 55
Accept: application/json
User-Agent: ai-path/0.1
{"subject": "VPN drops every afternoon", "priority": 2}Read it top to bottom:
| Part | Example | Meaning |
|---|---|---|
| Start line | POST /v1/tickets?priority=high HTTP/1.1 |
method, request target (path + query), protocol version |
| Headers | Host: tickets.example.com |
name: value pairs of metadata, one per line |
| Blank line | (empty) | marks the end of headers; everything after is the body |
| Body | {"subject": ...} |
the payload — for APIs usually JSON text |
The response has the same shape:
HTTP/1.1 201 Created
Content-Type: application/json
Content-Length: 85
X-Request-Id: req_9f2c41ab
{"id": 1045, "subject": "VPN drops every afternoon", "status": "open", "priority": 2}| Part | Example | Meaning |
|---|---|---|
| Status line | HTTP/1.1 201 Created |
protocol version, status code, reason phrase (cosmetic — clients read the number) |
| Headers | Content-Type: application/json |
metadata about the response |
| Body | {...} |
the result — JSON for most APIs |
Two details worth fixing now. First, Host is mandatory in HTTP/1.1 — one server can host many websites, and this header says which one you mean. Second, bodies are just bytes; Content-Type is how both sides agree how to read them. application/json means "this is JSON text"; text/event-stream means "this is an SSE stream" (3.10).
sequenceDiagram
participant C as Client (your code)
participant S as Server
C->>S: POST /v1/tickets HTTP/1.1<br/>Host, Authorization, Content-Type<br/>{"subject": "..."}
Note over S: route -> handler -> business logic -> database
S-->>C: HTTP/1.1 201 Created<br/>Content-Type: application/json<br/>{"id": 1045, ...}
Note over C: check status, parse JSON body1.3 Methods, and the two properties that matter#
The method (also called the verb) says what kind of action the request performs. There are eight standardised in RFC 9110 §9 plus PATCH (RFC 5789) — nine in all; the ones you will meet daily are:
| Method | Meaning | Safe? | Idempotent? | Typical use |
|---|---|---|---|---|
GET |
Retrieve a resource | ✅ | ✅ | GET /v1/tickets/1042, GET /v1/models |
HEAD |
Like GET but no body | ✅ | ✅ | check existence/size, validate links |
POST |
Submit data for processing | ❌ | ❌ | create a resource, run a query that is too big for a URL, call an LLM |
PUT |
Replace a resource entirely | ❌ | ✅ | PUT /v1/tickets/1042 with the full new object |
PATCH |
Modify part of a resource | ❌ | ❌* | PATCH /v1/tickets/1042 with {"status": "closed"} |
DELETE |
Remove a resource | ❌ | ✅ | DELETE /v1/tickets/1042 |
OPTIONS |
Ask what the server allows | ✅ | ✅ | CORS preflights (1.7) |
TRACE |
Diagnostics — echoes the request back | ✅ | ✅ | you'll almost never send it by hand |
CONNECT |
Open a tunnel through a proxy | ❌ | ❌ | you'll almost never send it by hand either |
* PATCH is not required to be idempotent by the spec, though many PATCH bodies are naturally idempotent ({"status": "closed"} applied twice gives the same result). Design yours to be.
Two properties do most of the work in API reasoning:
- Safe means "the request doesn't change anything on the server". Safe methods are the ones a browser may send automatically (pre-fetching, pre-connecting) and the ones caches may replay. Only
GET,HEAD,OPTIONSandTRACEare safe — TRACE is a diagnostic echo you'll never send by hand, but the spec classes it safe (and idempotent) like the others. - Idempotent means "sending the same request N times has the same effect as sending it once". Every safe method is idempotent too, and
PUT/DELETEjoin them:PUT /tickets/1042with the same body is idempotent: the resource ends up in the same state whether you call it once or five times.POST /ticketsis not: each call creates a new ticket. This is why retries are dangerous for POST and why APIs offer idempotency keys (3.6) — and why LLM calls, which are POSTs, can be billed twice if your client retries naively (03.8 covers this for provider calls).
1.4 URLs in full#
A URL (technically a URI; the terms are used loosely) has this anatomy:
https://api.openai.com:443/v1/responses?model=gpt-6-luna&stream=true#section-2
└─┬─┘ └──────┬───────┘ └┬┘ └─────┬──────┘ └──────────┬───────────┘ └─────┬──────┘
scheme host port path query string fragment| Part | Example | Sent to server? | Notes |
|---|---|---|---|
| Scheme | https |
determines TLS or not | http = plain, https = encrypted. Also ws/wss for WebSockets, file, ftp… |
| Host | api.openai.com |
✅ | domain or IP; resolved by DNS |
| Port | 443 |
✅ | optional; defaults are 80 (http), 443 (https). localhost:8000 means port 8000 |
| Path | /v1/responses |
✅ | the resource's location; /-separated segments |
| Query string | ?model=...&stream=true |
✅ | key=value pairs joined by &; used for filters, options, pagination |
| Fragment | #section-2 |
❌ | client-side only — browsers use it for anchors; never sent to the server |
A worked decomposition, run for real:
>>> import urllib.parse
>>> u = urllib.parse.urlsplit("https://api.openai.com:443/v1/responses?stream=true&limit=10#frag")
>>> u.scheme, u.netloc, u.path, u.query, u.fragment
('https', 'api.openai.com:443', '/v1/responses', 'stream=true&limit=10', 'frag')
>>> u.hostname, u.port
('api.openai.com', 443)Percent-encoding (RFC 3986): URLs may only contain a limited character set — letters, digits and -._~, plus a few structural characters (:/?#[]@!$&'()*+,;=). Anything else must be percent-encoded: each UTF-8 byte becomes % followed by two hex digits. Café becomes Caf%C3%A9, a space becomes %20 (or + in query strings built by HTML forms). If you build URLs by concatenating strings, a customer named O'Brien & Sons or a search for price < 100 will silently corrupt the request — always encode path segments and query values. In Python, urllib.parse.quote() does it:
>>> import urllib.parse
>>> urllib.parse.quote("/v1/tickets/Café Müller", safe="/")
'/v1/tickets/Caf%C3%A9%20M%C3%BCller'1.5 Status codes by class#
Every response carries a three-digit status code. The first digit is the class:
| Class | Meaning | Your reaction |
|---|---|---|
| 1xx Informational | "Got your headers, keep going" — rare in APIs | ignore |
| 2xx Success | the request worked | parse the body |
| 3xx Redirection | "the resource moved; go here" | follow or handle |
| 4xx Client error | you did something wrong | fix the request; retrying won't help (except 408, 429) |
| 5xx Server error | they did something wrong | retry with backoff, then escalate |
The codes every API uses, with what to do about each:
| Code | Name | What it means | What to do |
|---|---|---|---|
200 OK |
success | request succeeded; body holds the result | parse body |
201 Created |
success | a resource was created; Location header often points to it |
parse body |
202 Accepted |
success | work queued, not done — poll or wait for webhook | don't assume the result exists yet |
204 No Content |
success | succeeded, no body (common for DELETE) | don't try to parse a body |
301 / 302 / 307 / 308 |
redirect | moved permanently/temporarily | 301/308 = update your URL; 302/307 = follow once. 307/308 preserve method+body; 301/302 may turn POST into GET |
304 Not Modified |
redirect-ish | your cached copy is still fresh (used with ETag/If-None-Match) |
reuse cache |
400 Bad Request |
client | malformed request — bad JSON, wrong types, missing field | fix the request; log the error body |
401 Unauthorized |
client | not authenticated — missing/expired/invalid credentials | refresh or fix the key/token; don't retry blindly |
403 Forbidden |
client | authenticated but not allowed — wrong scope, permission denied | fix permissions; not a retryable error |
404 Not Found |
client | no such resource/path | check the URL; could be a deleted resource |
405 Method Not Allowed |
client | path exists but not for this method | check Allow header |
408 Request Timeout |
client | server gave up waiting for you | retry |
409 Conflict |
client | state conflict — duplicate, version mismatch, already exists | read the error; maybe fetch current state first |
413 Content Too Large (formerly Payload Too Large) |
client | body too big | shrink it, or use multipart upload |
415 Unsupported Media Type |
client | wrong Content-Type — you sent form data where JSON was expected |
fix the header |
422 Unprocessable Content |
client | syntactically fine, semantically wrong — validation failed | read the error body's field details |
429 Too Many Requests |
client | rate limited | wait Retry-After seconds (or exponential backoff); this is retryable |
500 Internal Server Error |
server | their bug | retry a few times, then report with the request ID |
502 Bad Gateway / 503 Service Unavailable / 504 Gateway Timeout |
server | upstream/proxy failure or overload | retry with backoff; 503 often pairs with Retry-After |
529-style provider codes |
server | provider-specific overload | check provider docs — treat like 503 |
1.6 Headers that matter#
Headers are where HTTP carries its metadata. You don't need all ~70 registered ones — these are the ones that appear in every API conversation:
| Header | Direction | What it does |
|---|---|---|
Host |
request | which site on a shared server (mandatory in HTTP/1.1) |
Content-Type |
both | media type of the body: application/json, application/x-www-form-urlencoded, multipart/form-data, text/event-stream |
Accept |
request | what response types you'll accept; Accept: application/json is polite but most APIs ignore it |
Authorization |
request | credentials — Bearer <token>, Basic <base64>, or provider-specific schemes |
User-Agent |
request | who you are: ai-path/0.1, python-httpx/0.28 — some APIs require it, some block blank ones |
Content-Length / Transfer-Encoding |
both | how big the body is / chunked streaming — set by the client library, not you |
Cache-Control |
both | caching rules: no-store (never cache — typical for API responses with auth), max-age=3600, no-cache (revalidate every time) |
ETag + If-None-Match |
response/request | a fingerprint of the body; client sends it back and gets 304 if unchanged — saves bandwidth |
Last-Modified + If-Modified-Since |
both | older, coarser version of the same idea |
Location |
response | where a 201/3xx points — e.g. the URL of the created resource |
Retry-After |
response | seconds (or a date) to wait before retrying — on 429, 503 |
X-RateLimit-Limit / -Remaining / -Reset |
response | the de-facto standard trio for quota info (not an official standard, but everywhere) |
X-Request-Id / Request-Id / x-request-id |
both | a unique ID for this call — quote it in bug reports and support tickets |
Set-Cookie |
response | the server asking the client to store a cookie (sessions, 00.5) |
Cookie |
request | cookies sent back |
Access-Control-* |
response | CORS headers — which origins may read this response from a browser (1.7) |
WWW-Authenticate |
response | on 401: what auth schemes the server accepts |
Allow |
response | on 405: which methods the path supports |
Content-Encoding |
both | compression applied: gzip, br (Brotli), zstd |
Date |
response | when the server sent it — used for clock-skew debugging |
Server |
response | what software answered — information leakage; good APIs omit it |
Custom X- headers are how APIs add their own metadata (anthropic-version, OpenAI-Organization, x-goog-api-key is a request header in Google's style). Provider-specific headers are covered in Part 4 and Part 6.
Body formats in one breath. Content-Type says how to read the body, and three values cover almost everything: application/json carries structured text; application/x-www-form-urlencoded carries flat name=value pairs URL-encoded (the classic HTML form POST — name=ada&role=eng); multipart/form-data exists for binary and mixed bodies — file uploads. The sender picks a random boundary string and the body becomes sections separated by --boundary, each with its own mini-headers including its own Content-Type — that's how one request carries a text field and a PNG. It's what curl -F file=@photo.png sends and what every browser <input type="file"> upload produces, and it's the format provider Files APIs expect when you upload documents for the model (03.6). You will never hand-write the boundary format — HTTP clients build it — but recognising multipart/form-data; boundary=----WebKitFormBoundary… in a Content-Type header tells you "this request carries files".
1.7 Content negotiation, cookies, redirects and compression#
Four mechanisms you will meet without realising:
- Content negotiation.
Accept(request) andContent-Type(both ways) let client and server agree on a representation:Accept: application/jsonasks for JSON, the server may replyContent-Type: application/problem+jsonfor errors even when it sentapplication/jsonfor success.Vary: Accepttells caches the response depends on it. - Cookies.
Set-Cookieon a response makes the browser (or HTTP client) store a small key=value and send it back asCookie:on later requests — that's how "stay logged in" works without re-authenticating (00.5 explains sessions). APIs that use cookies need a cookie-aware client (httpx.Client,requests.Session);urllib.requestneeds aCookieJarwired in — one more reason 01B.5 exists. - Redirects.
301(permanent),302(temporary),307/308(method-preserving).curldoesn't follow them unless you pass-L; browsers do automatically;urllib.requestfollows them except it won't resend a POST body to a different host. APIs return308when an endpoint moved — update your base URL rather than relying on the redirect forever. - Compression.
Accept-Encoding: gzip, br, zstdasks the server to compress the body;Content-Encodingsays which was used. JSON compresses ~5-10×, so this matters for big LLM responses. HTTP clients do it transparently — you almost never handle it by hand.
1.8 HTTP versions: 1.1, 2 and 3#
| HTTP/1.1 (RFC 9112; the protocol dates to 1997) | HTTP/2 (RFC 9113; the protocol dates to 2015, RFC 7540) | HTTP/3 (RFC 9114; the protocol dates to 2022) | |
|---|---|---|---|
| Transport | TCP | TCP | QUIC over UDP |
| Requests at once | one per connection, pipelining broken in practice | many streams multiplexed on one connection | same, plus connection migration |
| Headers | repeated verbatim every request | HPACK compressed, sent once | QPACK compressed |
| Head-of-line blocking | yes (one slow response stalls the connection) | at HTTP level no; TCP can still stall all streams | no — QUIC isolates streams |
| TLS | optional (HTTPS common) | mandatory in practice | mandatory |
| You see it as | HTTP/1.1 200 OK |
:status: 200 (binary framing; curl -v shows HTTP/2 200) |
HTTP/3 |
What matters practically: you almost never choose the version — browsers, curl and HTTP clients negotiate it (via ALPN during TLS). HTTP/2's multiplexing is why one httpx client can run many concurrent requests efficiently (03.9 leans on this), and HTTP/3's UDP base helps on lossy mobile networks. If curl -v shows HTTP/1.1 to an API that supports HTTP/2, your client or proxy is the reason — not the server.
Keep-alive is the older name for connection reuse: HTTP/1.1 defaults to persistent connections (Connection: keep-alive is implicit; Connection: close opts out), so one TCP connection carries many request/response pairs. Your client libraries pool these connections — which is why creating a new HTTP client per request is wasteful (01B.5 covers client lifecycle).
1.9 Timeouts: the habit that prevents hung programs#
Timeout: the single most important habit in network programming. Every call you make can hang forever: DNS stalls, the server accepts your connection and never replies, the network drops packets silently. A call without a timeout is a call that can hang your program, your job queue, your request handler — forever.
There are (at least) four distinct timeouts, and confusing them is a classic bug:
| Timeout | Covers | Typical value |
|---|---|---|
| Connect | TCP+TLS handshake to the server | 5–10 s |
| Read | waiting for the next chunk of the response | depends on the API — LLM calls need 60 s+ |
| Write | sending the request body | rarely hit; 30 s generous |
| Pool | waiting for a free connection from the client's pool | seconds |
An LLM call needs a long read timeout — a reasoning model can think for minutes — but a short connect timeout, because if you can't reach the host in 5 seconds the network is down, not slow. 03.8 §6 maps each provider SDK's defaults precisely; the rule here is just: never call without one.
1.10 Try it: send a request by hand#
Everything so far is visible on the wire. This script starts a tiny responder on 127.0.0.1, sends a hand-written HTTP/1.1 request over a raw socket, and prints exactly what went out and what came back — no libraries, just the protocol:
# raw_http_demo.py — stdlib only; run: python3 raw_http_demo.py
import socket
import threading
RESPONSE = (
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Content-Length: 54\r\n"
"Connection: close\r\n"
"\r\n"
'{"service": "tickets", "uptime_hours": 99, "ok": true}'
)
def serve_once(sock):
conn, _ = sock.accept()
conn.recv(65536) # read the request (we don't need to parse it)
conn.sendall(RESPONSE.encode())
conn.close()
sock.close()
def main():
srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", 8377)) # fixed port so the transcript is stable
srv.listen(1)
port = srv.getsockname()[1]
threading.Thread(target=serve_once, args=(srv,), daemon=True).start()
# This is the whole request: four lines of text, exactly as it goes on the wire.
request = (
f"GET /health HTTP/1.1\r\n"
f"Host: 127.0.0.1:{port}\r\n"
f"Accept: application/json\r\n"
f"Connection: close\r\n"
f"\r\n"
)
print("=== bytes sent ===")
print(request.replace("\r\n", "\\r\\n\n"))
with socket.create_connection(("127.0.0.1", port), timeout=5) as c:
c.sendall(request.encode())
raw = b""
while chunk := c.recv(65536):
raw += chunk
print("=== raw response ===")
print(raw.decode())
print("=== parts ===")
head, _, body = raw.partition(b"\r\n\r\n")
print("start line:", head.split(b"\r\n")[0].decode())
print("headers:")
for line in head.split(b"\r\n")[1:]:
print(" " + line.decode())
print("body:", body.decode())
if __name__ == "__main__":
main()=== bytes sent ===
GET /health HTTP/1.1\r\n
Host: 127.0.0.1:8377\r\n
Accept: application/json\r\n
Connection: close\r\n
\r\n
=== raw response ===
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 54
Connection: close
{"service": "tickets", "uptime_hours": 99, "ok": true}
=== parts ===
start line: HTTP/1.1 200 OK
headers:
Content-Type: application/json
Content-Length: 54
Connection: close
body: {"service": "tickets", "uptime_hours": 99, "ok": true}Every element from 1.2 is there: start line, headers, blank line, body — and the same four parts in the reply. The blank line matters: it is the only thing separating headers from body, so a body that itself contains blank lines is fine (that's why Content-Length or Transfer-Encoding must say where the body ends).
Part 2: JSON — the data format of APIs#
2.1 What JSON is#
JSON (JavaScript Object Notation) is a lightweight, text-based data format, standardised in RFC 8259 (and ECMA-404). It is the lingua franca of APIs: request bodies, response bodies, config files, log lines, eval datasets — nearly all of them are JSON. Three properties explain its dominance:
- It is text. A JSON document is a sequence of Unicode characters — you can read it,
catit, put it in git, send it over any protocol. - It is language-independent. Every language has a JSON parser; the same bytes mean the same data in Python, JavaScript, PHP, Go, Rust and Java.
- It is self-describing. Objects carry their field names, so
{"status": "open"}tells you what"open"refers to without a schema.
A JSON document is one value: an object, an array, a string, a number, true, false or null. In practice, API bodies are almost always an object at the top level.
2.2 What JSON is not#
This is where most first parse errors come from. JSON is deliberately strict — it was designed to be parsed by machines, not written by humans:
| Not allowed | Why people try it anyway | What to write instead |
|---|---|---|
Comments (//, /* */, #) |
JSON looks like JavaScript | no comments exist; put explanations in a sibling field or docs |
Trailing commas ({"a": 1,}) |
Python dicts and JS allow them | {"a": 1} |
Single quotes ({'a': 1}) |
Python/JS habit | "a" — strings must use double quotes |
NaN, Infinity, -Infinity |
IEEE floats exist | JSON has no representation; use null or omit |
Unquoted keys ({a: 1}) |
JavaScript object literal | {"a": 1} |
Hex/octal/binary numbers (0x10, 0o17) |
C/Python habits | decimal only: 16, 15 |
Leading zeros (007) |
habit | 7 |
+ sign or leading . (+1, .5) |
habit | 1, 0.5 |
| Tabs/newlines raw inside strings | habit | escape them: \t, \n |
Python's json module is looser than the JSON standard on both writes and reads by default — a genuinely useful pair of facts:
json.dumpsrefusesNaN/Infinityonly if you passallow_nan=False; by default it emits the bare tokensNaN,Infinity,-Infinity, which are not valid JSON — a strict parser (JavaScript'sJSON.parse, Go'sencoding/json, most providers) will reject your request.json.loadsacceptsNaN,Infinityand-Infinityby default, so Python will happily read a document other tools reject.
# json_nan.py — run: python3 json_nan.py
import json
bad = {"value": float("nan")}
print("dumps default:", json.dumps(bad)) # emits NaN — invalid strict JSON
try:
json.dumps(bad, allow_nan=False)
except ValueError as e:
print("allow_nan=False:", e)
print("loads default:", json.loads('{"v": NaN}')) # Python accepts what JSON forbids
def reject_constant(c):
raise ValueError(f"non-JSON constant {c!r} is not allowed")
try:
json.loads('{"v": NaN}', parse_constant=reject_constant)
except ValueError as e:
print("loads strict rejects:", e)dumps default: {"value": NaN}
allow_nan=False: Out of range float values are not JSON compliant: nan
loads default: {'v': nan}
loads strict rejects: non-JSON constant 'NaN' is not allowedparse_constant is called for NaN/Infinity/-Infinity; raising inside it makes json.loads reject them — the read-side counterpart of allow_nan=False. For production code, pass a parse_constant that raises — or better, never let NaN into data you serialize.
2.3 json.loads and json.dumps in Python#
The standard library's json module has exactly two functions you need daily:
json.dumps(obj)— dump a Python object to a string of JSON (thesstands for "string").json.loads(text)— load a JSON string back into a Python object.
The mapping between JSON and Python types is small and worth memorising:
| JSON | Python | Notes |
|---|---|---|
object {...} |
dict |
keys always str |
array [...] |
list |
order preserved |
string "..." |
str |
Unicode; escapes decoded |
number 42, -3.5 |
int / float |
no distinction in JSON; Python picks by presence of ./e |
true / false |
True / False |
lowercase in JSON! |
null |
None |
A real round trip, run for real:
# json_roundtrip.py — run: python3 json_roundtrip.py
import json
ticket = {
"id": 1042,
"subject": "Cannot log in — 'Café Müller' says \"reset password\"",
"status": "open",
"priority": 2,
"tags": ["login", "urgent"],
"assignee": None,
"resolved": False,
"score": 0.875,
}
print(json.dumps(ticket, ensure_ascii=False))
print(json.dumps(ticket, indent=2, sort_keys=True, ensure_ascii=False))
back = json.loads(json.dumps(ticket))
print("same dict?", back == ticket, "| types:", type(back).__name__, type(back["resolved"]).__name__){"id": 1042, "subject": "Cannot log in — 'Café Müller' says \"reset password\"", "status": "open", "priority": 2, "tags": ["login", "urgent"], "assignee": null, "resolved": false, "score": 0.875}
{
"assignee": null,
"id": 1042,
"priority": 2,
"resolved": false,
"score": 0.875,
"status": "open",
"subject": "Cannot log in — 'Café Müller' says \"reset password\"",
"tags": [
"login",
"urgent"
]
}
same dict? True | types: dict bool(Both calls pass ensure_ascii=False, so —, é and ü stay literal UTF-8 — the default True would emit \u2014-style escapes instead. Both forms are valid JSON; literal text is what most APIs prefer for readability.)
Options you will actually use:
| Argument | Effect |
|---|---|
indent=2 |
pretty-print for humans and diffs |
sort_keys=True |
deterministic key order — stable diffs, stable hashes |
ensure_ascii=False |
keep Unicode literal instead of \uXXXX escapes |
separators=(",", ":") |
maximally compact (default already close) |
allow_nan=False |
refuse to emit invalid JSON (recommended) |
json.loads(text, parse_float=Decimal) |
keep numbers exact — see 2.4 |
python3 -m json.tool is the zero-code pretty-printer: echo '{"a":1}' | python3 -m json.tool reformats any JSON on stdin — useful for eyeballing API output in a terminal.
dumps only knows the six mapped types. Everything else — datetime, Decimal, set, bytes, arbitrary objects — raises TypeError: Object of type X is not JSON serializable. This is the single most common json error in real code (a timestamp or a Decimal slips into a payload and the whole request dies). Convert first — dt.isoformat(), str(), list(s) — or pass default= for a fallback serializer. Two wrinkles worth knowing: a tuple is accepted (it becomes a JSON array), and non-string dict keys are silently coerced to strings:
# json_types.py — run: python3 json_types.py
import json
import datetime
from decimal import Decimal
for value in [datetime.datetime(2026, 11, 6, 14, 30), Decimal("19.99"), {1, 2}, b"pdf"]:
try:
json.dumps({"v": value})
except TypeError as e:
print(f"{type(value).__name__:>10}: {e}")
print(json.dumps({"created": datetime.datetime(2026, 11, 6, 14, 30)}, default=str)) datetime: Object of type datetime is not JSON serializable
Decimal: Object of type Decimal is not JSON serializable
set: Object of type set is not JSON serializable
bytes: Object of type bytes is not JSON serializable
{"created": "2026-11-06 14:30:00"}default=str is a fine quick-and-dirty fallback for logs — but wrong for APIs, where the wire shape is a contract: decide deliberately whether a timestamp goes out as an ISO-8601 string, money as integer cents, and so on. For whole .json files, json.dump(obj, f) and json.load(f) are the file-object twins of dumps/loads — same functions, a file instead of a string; the dumps/loads pair is what you want for API bodies and JSONL lines.
2.4 Numbers and precision#
JSON numbers have no separate integer/float types — 42 and 42.0 are both just "number". Two precision traps follow:
- Floats are IEEE-754 doubles everywhere.
0.1 + 0.2 != 0.3applies to JSON too:{"price": 19.99}is stored as the nearest double, not the decimal you typed. For money, keep cents as integers (1999) or decimal strings — never rely on float equality. - Integers beyond 2^53 lose precision in JavaScript. JSON itself allows arbitrary-size integers, but
JSON.parsein JS and some other parsers silently round anything above 9,007,199,254,740,992. APIs that might return huge IDs either keep them as strings ("id": "9223372036854775807") or accept the rounding. When you see an ID quoted in JSON, that's why.
If exact decimal arithmetic matters (invoices, prices), Python's json.loads(text, parse_float=decimal.Decimal) keeps every digit — mention it now; 01A covers decimal properly.
2.5 Strings, Unicode and escaping#
JSON strings are sequences of Unicode code points, encoded as UTF-8 on the wire. Inside a string, only three characters must be escaped: " (as \"), \ (as \\), and control characters below U+0020 (as \n, \t, \u0001…). Everything else — including emoji and non-Latin scripts — may appear literally or as \uXXXX escapes (surrogate pairs for characters above U+FFFF, e.g. \ud83d\ude00 for 😀). json.dumps escapes non-ASCII by default (ensure_ascii=True) — valid but noisy; ensure_ascii=False emits UTF-8 directly.
Three rules of thumb:
- JSON is UTF-8. If a server sends bytes that aren't valid UTF-8, it's broken — declare/expect
charset=utf-8(application/jsonimplies UTF-8 by RFC 8259 anyway). - Never build JSON by string concatenation.
'{"name": "' + name + '"}'breaks on quotes, backslashes and newlines inname. Alwaysjson.dumps. - Key order is not guaranteed. RFC 8259 says objects are unordered; don't rely on
{"a":1,"b":2}staying in that order through a round trip (Python dicts preserve insertion order, but other languages and re-serializations may not). If order matters, use an array of pairs or an explicitorderfield.
2.6 JSON Lines (JSONL)#
JSONL (JSON Lines, .jsonl) is not a JSON extension — it's a convention: one complete JSON value per line, newline-terminated. Where a .json file is one document, a .jsonl file is a stream of documents:
{"id": "t-001", "input": "My invoice total is wrong", "expected": "billing"}
{"id": "t-002", "input": "How do I reset my password?", "expected": "account"}
{"id": "t-003", "input": "The app crashes on launch", "expected": "bug"}Why the AI world loves it:
- Append-friendly. Add a line, done — no need to re-serialize a giant array.
- Stream-friendly. Read line by line; never load the whole file. A 10-million-line eval set processes in constant memory.
- Failure-local. One malformed line breaks one record, not the whole file.
- Diff-friendly. Git shows exactly which case changed.
This is the file format of provider batch APIs (03.9: one request object per line into /v1/batches), LLM eval datasets (10A.2 §1.4 recommends JSONL in git as the source of truth), and structured logs (03.10 logs JSON lines). Reading and writing it is a few lines of Python — and the same script shows why the format is stream-friendly:
# jsonl_demo.py — run: python3 jsonl_demo.py
import json
cases = [
{"id": "t-001", "input": "My invoice total is wrong", "expected": "billing"},
{"id": "t-002", "input": "How do I reset my password?", "expected": "account"},
{"id": "t-003", "input": "The app crashes on launch", "expected": "bug"},
]
print("== write JSONL ==")
with open("cases.jsonl", "w", encoding="utf-8") as f:
for c in cases:
f.write(json.dumps(c) + "\n") # one compact JSON object per line
print(open("cases.jsonl", encoding="utf-8").read(), end="")
print("== read JSONL back, line by line ==")
with open("cases.jsonl", encoding="utf-8") as f:
for i, line in enumerate(f, 1):
obj = json.loads(line) # each line parses independently
print(f"line {i}: id={obj['id']!r} expected={obj['expected']!r}")
print("== stream-friendly: no need to load the whole file ==")
count = sum(1 for _ in open("cases.jsonl", encoding="utf-8"))
print(f"{count} cases, one per line")== write JSONL ==
{"id": "t-001", "input": "My invoice total is wrong", "expected": "billing"}
{"id": "t-002", "input": "How do I reset my password?", "expected": "account"}
{"id": "t-003", "input": "The app crashes on launch", "expected": "bug"}
== read JSONL back, line by line ==
line 1: id='t-001' expected='billing'
line 2: id='t-002' expected='account'
line 3: id='t-003' expected='bug'
== stream-friendly: no need to load the whole file ==
3 cases, one per line2.7 jq: JSON at the command line#
jq is the grep/sed of JSON — it parses a document and lets you slice it with a small expression language. It is worth installing (brew install jq on macOS, apt install jq on Debian/Ubuntu, winget install jqlang.jq on Windows — check the official jqlang.github.io/jq page for current instructions, as of November 2026). With sample.json containing {"data": [{"id": 1042, "subject": "Cannot log in", "status": "open", "priority": 1}, ...], "total": 3}:
$ jq '.data[] | select(.status == "open") | .subject' sample.json
"Cannot log in"
"Invoice missing VAT"
$ jq -r '.data | length' sample.json
3
$ jq 'has("total")' sample.json
true
$ jq '.data[0]' sample.json
{
"id": 1042,
"subject": "Cannot log in",
"status": "open",
"priority": 1
}The three jq habits that cover 90% of use: .field and .[] to descend, select(cond) to filter, -r to emit raw strings (no quotes) for shell pipelines. You'll use it constantly on API responses in 00.2 and when reading LLM eval output in 10A.x.
2.8 Other formats compared#
JSON won the API war, but it isn't the only data format you'll meet. One table to place them all:
| Format | Looks like | Strengths | Where you meet it |
|---|---|---|---|
| JSON | {"a": 1} |
universal, strict, every language parses it | API bodies — the default |
| JSONL | one object per line | streaming, append-friendly | batch files, logs, eval sets |
| YAML | a: 1 indented |
human-friendly, comments allowed | config files, GitHub Actions, Kubernetes, OpenAPI specs |
| TOML | a = 1 sections |
unambiguous, great for config | pyproject.toml, Rust/Go configs |
| CSV/TSV | a,b,c rows |
spreadsheets, flat tables | exports, simple datasets — breaks on nested data |
| XML | <a>1</a> |
old enterprise standard, namespaces, schemas | legacy SOAP APIs, Office docs, Android layouts |
| Protocol Buffers | binary + .proto schema |
compact, fast, typed, versioned | gRPC APIs, some high-throughput internal APIs |
| MessagePack | binary JSON-like | compact JSON superset | some realtime/game APIs |
| HTML/Markdown | markup | human-readable documents | web pages, docs, prompts |
Decision rule: APIs speak JSON (occasionally Protobuf for gRPC — 3.10); config speaks YAML or TOML; flat tables speak CSV; everything else is a specialist you meet on demand. Don't write a YAML parser by hand — Python's pyyaml and tomllib (stdlib since 3.11) exist; 01B.1 covers them.
2.9 JSON Schema: describing the shape of JSON#
Raw JSON tells you what the data is, not what it should be. JSON Schema is the standard language (a JSON document itself, specified by the JSON Schema community at json-schema.org — the current dialect is 2020-12; I-JSON, RFC 7493, is a related but separate interoperability profile) for describing allowed shapes: which fields exist, their types, required fields, enums, ranges, nested objects.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "subject", "status"],
"properties": {
"id": {"type": "integer"},
"subject": {"type": "string", "minLength": 1},
"status": {"type": "string", "enum": ["open", "closed"]},
"priority": {"type": "integer", "minimum": 1, "maximum": 5}
},
"additionalProperties": false
}Read it as a contract: an object that must have id, subject, status; status must be "open" or "closed"; priority is optional but 1–5 if present; no extra fields allowed. This is the same machinery behind OpenAPI request/response definitions and — crucially for this path — every LLM provider's structured-output feature: you send a JSON Schema (usually generated from a Pydantic model) and the provider constrains the model's output to match it. 03.4 is the complete treatment; the keywords you'll meet there — $ref, anyOf, additionalProperties, enum — are the same ones as above.
Python validates JSON against a schema with the jsonschema library (third-party; install with uv add jsonschema — you'll meet it properly in 01B.6 via Pydantic, which generates schemas for you). For now, the mental model is enough: schema = contract, JSON = data, validation = the bouncer at the door.
2.10 Validating JSON and common parse errors#
In real code you never call json.loads bare — you wrap it, because "the API returned something unexpected" is a normal Tuesday:
import json
def parse_ticket(text: str) -> dict:
try:
obj = json.loads(text)
except json.JSONDecodeError as e:
raise ValueError(f"response was not valid JSON at line {e.lineno} col {e.colno}: {e.msg}") from e
if not isinstance(obj, dict) or "id" not in obj:
raise ValueError("JSON parsed but is not a ticket object")
return objThe layered view — parse → type-check → schema-validate → semantic-check — is exactly how 03.4 treats model output, and how 05.10 treats ingested data. json.JSONDecodeError gives you lineno, colno, pos and msg — quote them in bug reports; they turn "it didn't work" into "line 3, column 47: Expecting property name enclosed in double quotes".
Common parse errors you'll actually see, with causes:
| Error message (Python) | Usually means |
|---|---|
Expecting property name enclosed in double quotes |
single quotes, unquoted keys, trailing comma |
Expecting value |
{"a": }, NaN where parser is strict, missing comma |
Extra data |
two JSON documents concatenated; JSONL fed to json.loads; trailing text after the object |
Invalid \escape |
bad escape like \x; or a Windows path C:\new unescaped |
Unterminated string |
raw newline inside a string, or a truncated body |
the JSON object must be str, bytes or bytearray |
you passed bytes with a BOM, or a dict to loads |
Part 3: REST and API design#
Deep-dive
HTTP gives you the envelope; REST is the set of conventions for what goes inside it. "REST API" is the phrase you'll hear for nearly every API you'll call — including all four LLM providers — so this part is the vocabulary of API design: how resources are named, how lists are paginated, how errors are shaped, and how the main architectural styles compare.
3.1 Resources, collections and URL design#
REST (Representational State Transfer — Roy Fielding's 2000 dissertation gave it its name) models the API as a set of resources: nouns the client can fetch or change. The conventions:
- Nouns in the path, not verbs.
/v1/tickets/1042names a thing;/v1/getTicket?id=1042is RPC-style thinking leaking into a URL. The method carries the verb (GETreads,POSTcreates,PUT/PATCHupdates,DELETEremoves). - Collections are plural nouns.
GET /v1/ticketslists;POST /v1/ticketscreates;GET /v1/tickets/1042fetches one. Nesting shows ownership:/v1/tickets/1042/messagesis "messages belonging to ticket 1042". - The path is hierarchical and stable.
/v1/is a version prefix (3.5);/models,/chat/completions,/v1/messagesare the resource names each provider chose. - Query strings hold modifiers, not identity.
?status=open&limit=10&sort=-createdfilters and shapes the collection; the resource itself lives in the path.
Against our fake tickets API from 5.4:
| Request | Meaning |
|---|---|
GET /v1/tickets |
list all tickets |
GET /v1/tickets?status=open&limit=2 |
list open tickets, at most 2 |
GET /v1/tickets/1042 |
one ticket |
POST /v1/tickets body {"subject": "...", "priority": 2} |
create a ticket → 201 + the created object |
PATCH /v1/tickets/1042 body {"status": "closed"} |
change one field |
DELETE /v1/tickets/1042 |
remove it → 204 |
This maps almost perfectly onto the LLM APIs you'll meet in Part 6: POST /v1/responses creates a response (an inference result is treated as a created resource — which is also why OpenAI's Responses API has a GET /v1/responses/{id} to fetch stored results), GET /v1/models lists models, POST /v1/messages/batches creates a batch job. The verbs-nouns discipline is why "call the completions endpoint" and "create a response" are the same idea wearing different clothes.
3.2 Request and response bodies#
For APIs that carry JSON, the body is where the real content lives. Conventions worth internalising:
- Requests: a JSON object,
Content-Type: application/json, fields named insnake_case(OpenAI, Anthropic) orcamelCase(Gemini uses camelCase insidegenerationConfig— check each provider's docs; 00.8 is entirely about reading them well). - Responses: usually
{"data": [...]}for lists and the bare object for one item — but conventions differ: OpenAI wraps lists in{"object": "list", "data": [...]}, Anthropic uses{"data": [...], "has_more": true, "first_id": ...}for pagination, Gemini returns{"candidates": [...]}. There is no universal envelope; learn to read each provider's shape once (03.1 does this exhaustively). - Empty vs absent vs null.
204means no body at all."field": nullmeans "present, value is nothing". A missing key means "not provided/unknown". APIs blur these — when debugging, dump the raw JSON and look, don't assume.
3.3 Pagination: offset, page and cursor#
Lists are never infinite — GET /v1/models returns dozens, GET /v1/tickets could return millions. APIs paginate; the three schemes:
| Scheme | Looks like | Pros | Cons |
|---|---|---|---|
| Offset/limit | ?offset=50&limit=25 or ?page=3&per_page=25 |
simple, random access ("jump to page 7") | slow deep pages (the DB counts/skips everything before); items shift if the list changes mid-scroll ("page 2 shows a duplicate of page 1's last item") |
| Cursor/keyset | ?cursor=eyJpZCI6MTA0Mn0&limit=25 → response has "next_cursor": "..." |
stable under inserts/deletes; fast at any depth | opaque — you can't jump to "page 50"; cursor encodes "after this item" |
Page tokens / next_page_token |
Google-style: response gives nextPageToken, you send it back |
same stability as cursor, sometimes human-readable | provider-specific |
The modern default is cursor pagination — Anthropic's Messages API uses has_more/last_id cursors, OpenAI's list endpoints return has_more + after cursors, and Gemini uses nextPageToken. Offset survives in internal admin APIs and SQL-shaped thinking. When you build your own API (01B.7), choose cursor unless you genuinely need numbered pages.
3.4 Filtering, sorting and searching#
Query parameters carry the modifiers:
- Filtering:
?status=open&priority__gte=2— each provider names operators differently (priority__gtedouble-underscore is Django-style; others usemin_priority=). Read the docs' parameter table, not your intuition. - Sorting:
?sort=-created_at(-= descending is a widespread convention, but not universal — some usesort=created_at:desc). - Searching:
?q=VPNfull-text, or structured filters. LLM APIs add their own: OpenAI'sGET /v1/responses/{id}doesn't search, but fine-tuning and batch endpoints do; vector "search" is embeddings, a different module entirely (06.x).
A good API documents every parameter's name, type, allowed values and default in its reference — that's what 00.8 trains you to read.
3.5 Versioning#
APIs change; clients can't all upgrade at once. Versioning is how providers evolve without breaking you:
- URL path versioning (most common):
/v1/messages,/v2/...— OpenAI, Anthropic, Gemini'sv1beta/v1all do this. - Header versioning:
anthropic-version: 2026-10-21— Anthropic dates its versions because behaviour changes are frequent; the header pins your semantics. - Unversioned + dates: some APIs ship continuous change with deprecation notices.
Rules for you as a caller: put the version where the provider puts it, never mix versions casually, and read the changelog/deprecations page before upgrading — 00.8 covers changelogs; 03.1 §9.1 explains Anthropic's dated versions specifically. As an API designer (later, in 01B.7), never break a released version: add fields, don't rename them; deprecate with notice.
3.6 Idempotency keys#
Retrying a POST can double-charge, double-create, double-send. The industry answer is the idempotency key: a client-generated unique ID (UUID) sent in a header — Idempotency-Key: 8f3c... — that the server records with the first result. A retry carrying the same key returns the first result instead of acting again. Stripe built its reputation on this; payment and provisioning APIs all offer it.
POST /v1/charges
Idempotency-Key: 9b2e7c1a-...
{"amount": 2000, "currency": "usd"}Rules: the key must be unique per logical operation (generate one when the user clicks "pay", reuse it across retries of that same click), scoped to your account, and retained by the server for a window (Stripe keeps them ~24h). LLM inference APIs don't offer idempotency keys — each POST is a fresh, billed generation; retrying a timed-out call can pay twice, which is why 03.8 §11 is called "Idempotency and duplicate charges" and teaches you to only retry when the outcome is certain (connection refused before send) or acceptable (you'll dedupe yourself via stored response IDs).
3.7 Errors: a consistent error body and Problem Details#
The status code says what class of failure; the body should say what actually happened. Good APIs return a consistent error shape on every endpoint — typically an object with a machine-readable code/type, a human message, and often per-field details:
{
"error": {
"type": "invalid_request_error",
"code": "missing_required_parameter",
"message": "Missing required parameter: 'model'.",
"param": "model"
}
}This is the shape OpenAI uses; Anthropic returns {"type": "error", "error": {"type": "invalid_request_error", "message": "..."}}; Gemini returns {"error": {"code": 400, "message": "...", "status": "INVALID_ARGUMENT"}}. Learn each once — 03.1 tabulates them.
The standardised version is Problem Details (RFC 9457, which obsoleted RFC 7807): a JSON document with type (a URI identifying the problem kind), title (short summary), status (the HTTP code repeated), detail (instance-specific explanation) and instance (URI identifying this occurrence), served as application/problem+json. You don't have to adopt it — but when you see application/problem+json in docs, now you know it's the IETF standard error format, not a provider quirk. Design rule for your own APIs later: one error envelope, documented, with a stable machine code — clients branch on code, humans read message.
3.8 Rate limits and 429#
Nearly every API limits how fast you may call it, measured in requests/minute and/or tokens/minute for LLM APIs. The signals:
429 Too Many Requests— you hit the limit. The response should carryRetry-After: <seconds>; many also sendX-RateLimit-Remaining: 0andX-RateLimit-Reset: <epoch>so you can pace yourself before hitting the wall.- Rate-limit headers on every response —
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset(de-facto standard; some APIs useratelimit-*IETF draft headers or provider-specific names — read the docs). - Two kinds of 429 — "slow down, retry shortly" (throughput limit) vs "you're out of quota/credit" (hard limit, retrying won't help). Providers distinguish them in the error body's
code/type. 03.8 §4.2 is the definitive treatment for LLM APIs.
The engineering response is always the same shape: honour Retry-After if present, else exponential backoff with jitter, bounded — and that's precisely 01B.9's subject and 03.8's for LLM calls. Never while True: retry.
3.9 HATEOAS: awareness only#
HATEOAS (Hypermedia As The Engine Of Application State) was Fielding's most radical REST constraint: responses should contain links to related actions ({"_links": {"cancel": {"href": "/v1/jobs/9/cancel"}}}), so clients discover what they can do rather than hard-coding URLs. In practice almost nobody implements it — GitHub's API comes closest — and you can safely treat it as vocabulary, not a design requirement. What survives from it: include URLs/IDs in responses so clients can act on what they got (id, url, next_cursor fields are the pragmatic version).
3.10 REST vs RPC vs GraphQL vs gRPC vs WebSockets vs SSE#
"API" covers several architectures. The comparison that matters:
| Style | Shape | Transport | Data format | When it's used |
|---|---|---|---|---|
| REST | resources + methods | HTTP/1.1–3 | JSON (usually) | public APIs, CRUD, most web services — including all four LLM providers' main endpoints |
| RPC | "call this function" — getTicket(1042) |
HTTP (JSON-RPC, XML-RPC) or binary | JSON/XML | internal services, legacy; conceptually "a function call over the wire" |
| GraphQL | one endpoint, client writes a query describing exactly the fields it wants | HTTP POST | JSON | front ends that need flexible field selection; GitHub, Shopify expose it |
| gRPC | strongly-typed service methods defined in .proto files |
HTTP/2 | Protocol Buffers (binary) | high-performance internal microservices (Google, many infra companies) |
| WebSockets | persistent bidirectional channel | WS/WSS (TCP+TLS) | any frames — JSON text common | chat, games, collaborative editing, voice/realtime audio (09.x) |
| SSE (Server-Sent Events) | server pushes a stream of events down one HTTP response | plain HTTP, text/event-stream |
text events, usually JSON data: lines |
LLM streaming, notifications, live dashboards — one-directional server→client |
The LLM connection: every provider's streaming mode is SSE — POST the same request with "stream": true, the response becomes Content-Type: text/event-stream and the server writes events as the model generates. One worked example of the raw format (what 03.3 unpacks per provider):
POST /v1/chat/completions HTTP/1.1
Host: api.openai.com
Authorization: Bearer sk-...
Content-Type: application/json
{"model": "gpt-6-luna", "stream": true,
"messages": [{"role": "user", "content": "Say hi in three words"}]}
→ HTTP/1.1 200 OK
Content-Type: text/event-stream
data: {"id":"chatcmpl-...","choices":[{"delta":{"role":"assistant"},"index":0}]}
data: {"id":"chatcmpl-...","choices":[{"delta":{"content":"Hello"},"index":0}]}
data: {"id":"chatcmpl-...","choices":[{"delta":{"content":"there"},"index":0}]}
data: {"id":"chatcmpl-...","choices":[{"delta":{},"finish_reason":"stop","index":0}],"usage":{...}}
data: [DONE]Each data: line is one JSON event; a blank line ends the event; data: [DONE] is OpenAI's sentinel for "stream over". The response headers arrive immediately — that's the whole point: your UI shows the first token in ~200 ms instead of waiting 10 s for the full answer. SSE is HTTP, so it inherits auth headers, status codes, gzip and timeouts — no new machinery. 03.3 §2.1 is the full SSE spec in one page; §2.2 captures the raw bytes of all five provider stream formats.
3.11 Webhooks#
A webhook inverts the call direction: instead of you polling "is my job done?", the provider POSTs to your URL when something happens — a batch finished, a payment cleared, a voice session ended. It's just an HTTP request your server must expose:
POST /hooks/openai-batch HTTP/1.1
Host: your-app.example.com
Content-Type: application/json
X-Signature: sha256=9f2c...
{"id": "batch_abc123", "status": "completed", "output_file_id": "file-..."}00.5 §4.4 covered why your endpoint must be public, verified and idempotent — this section adds the wire level. On the wire, three rules make webhooks safe:
- Verify the signature. Providers sign the raw body with a shared secret — typically an HMAC (Stripe's
Stripe-Signature, GitHub'sX-Hub-Signature-256, or a provider-specific header). Verify against the raw bytes before parsing or acting; Stripe-style signatures also cover a timestamp so you can reject replays outside a freshness window. - Dedupe on the event
id. Delivery is at-least-once: the same event can arrive twice (provider retry, your slow ack). Store processed IDs and skip repeats — the event's ownidfield is your idempotency key. - Ack fast. Return
2xxquickly and do slow work asynchronously (enqueue it), or the provider retries and eventually disables the endpoint.
03.9 §13.6 catalogs what each LLM provider's webhooks send; 05.9 uses them in ingestion pipelines.
sequenceDiagram
participant You as Your app
participant Prov as Provider
You->>Prov: POST /v1/batches (start job)
Prov-->>You: 202 Accepted + job id
Note over You,Prov: polling loop (wasteful) OR
Prov->>You: POST /hooks/batch-done<br/>X-Signature + event JSON
You->>You: verify signature, dedupe, enqueue work
You-->>Prov: 200 OK (ack fast)Part 4: Authentication in APIs#
"Auth" on an API answers one question on every request: who is calling, and what may they do? (authentication vs authorization — 00.5 separates them). The schemes you'll meet, roughly in order of sophistication:
| Scheme | How it looks | Used for |
|---|---|---|
| API key in a header | X-API-Key: sk-... or a provider-specific header |
server-to-server, simple billing identity |
| Bearer token | Authorization: Bearer <token> |
the modern default: API keys sent this way, OAuth access tokens, JWTs |
| Basic auth | Authorization: Basic base64(user:pass) |
legacy; still on some internal tools, Git over HTTPS |
| OAuth 2.0 | get a short-lived access token from an auth server, send it as Bearer | "Log in with Google", third-party access without sharing your password |
| Signed requests | HMAC signature over method+path+body+timestamp in headers | AWS SigV4, webhook verification, high-security APIs |
| mTLS / workload identity | the TLS certificate is the identity | service meshes, cloud platforms (AWS/GCP/Azure keys) |
4.1 The four you'll actually use#
API key. A long random string identifying your account (and project). It is a secret bearer credential: whoever holds it can spend your money. Send it in a header — never the URL (1.4). Store it in an environment variable or .env, never in source (00.4 and 03.1 Part 3 own the full hygiene treatment).
Bearer token. Authorization: Bearer <token> means "the credential is this opaque token — don't parse it, just forward it". JWTs (JSON Web Tokens, RFC 7519) are the common case: a signed JSON blob you can decode (header.payload.signature, base64url) to see claims like exp (expiry) and scope — but you verify the signature, you don't trust the contents blindly. LLM providers' API keys are sent as bearer tokens even though they're static keys.
Basic auth. Authorization: Basic + base64(username:password). Base64 is encoding, not encryption — echo dXNlcjpwYXNz | base64 -d gives user:pass. It's fine inside HTTPS (the transport encrypts it), useless without. Still common for Git remotes and internal dashboards; rare in modern public APIs.
OAuth 2.0 (RFC 6749). The "Log in with Google" flow: your app redirects the user to the provider's auth server, they consent, the auth server redirects back with a code, your backend exchanges the code for an access token, and you call the API with Authorization: Bearer <access_token>. The point: the user never gives your app their password, and you can request narrow scopes ("read calendar" not "everything"). You will mostly consume OAuth when calling Google/GitHub on a user's behalf; 12.x covers the security side.
Signed requests (awareness): AWS-style APIs compute HMAC_SHA256(secret, method + path + timestamp + body_hash) and send it in a header; the server recomputes and compares. It proves the caller holds the secret and that the request wasn't tampered with — the pattern behind webhook signature verification (3.11).
4.2 Where each LLM provider puts its key#
Verified against the official docs as of November 2026 — the full wire treatment is 03.1 §1.2:
| Provider | Endpoint | Auth header | Extra required headers |
|---|---|---|---|
| OpenAI | POST https://api.openai.com/v1/responses |
Authorization: Bearer <key> |
— |
| OpenAI | POST https://api.openai.com/v1/chat/completions |
Authorization: Bearer <key> |
— |
| Anthropic | POST https://api.anthropic.com/v1/messages |
Authorization: Bearer <key> (SDK 2.x) or legacy x-api-key: <key> |
anthropic-version: 2026-10-21 |
| Gemini | POST https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent |
x-goog-api-key: <key> |
— |
| OpenRouter | POST https://openrouter.ai/api/v1/chat/completions |
Authorization: Bearer <key> |
— |
Two details worth remembering: Anthropic requires anthropic-version on every request (the SDKs set it; raw HTTP must too), and Gemini puts the model name in the URL path with a colon-action (models/gemini-3.8-flash:generateContent) — Google's API style, different from everyone else's "model" field in the body.
4.3 Auth in the browser vs server-side#
A key in browser JavaScript is a key published to the world — anyone can open DevTools and read it. Browser apps must call your backend, and your backend calls the provider with the key (00.5 drew this architecture; 03.1 §3.5 is the deep treatment). CORS exists precisely to stop arbitrary websites from reading responses cross-origin — but it doesn't stop them from sending requests, which is why "the key is safe because CORS blocks it" is wrong: the request still happens and still bills you.
Part 5: Calling APIs by hand#
Before any SDK, learn to call an API with the tools already on your machine. This part builds a fake tickets API on 127.0.0.1 (your own machine — no internet, no key) and calls it three ways.
5.1 curl: the universal API client#
curl turns a URL into an HTTP request from the terminal. The flags you will use daily:
| Flag | Does |
|---|---|
-X POST / -X GET / -X DELETE |
set the method (GET is default) |
-H "Name: value" |
add a header (repeatable) |
-d '{...}' / --data |
request body; implies POST and sets Content-Type: application/x-www-form-urlencoded — add -H "Content-Type: application/json" for JSON |
-i |
include response headers in the output |
-v |
verbose: print the full request/response trace to stderr — the debugging tool |
-w '%{http_code} %{time_total}' |
print status code and total time after the body |
-o file / -O |
save body to file / remote filename |
-L |
follow redirects |
--fail / -f |
return exit code 22 on HTTP errors instead of printing the body |
--max-time 30 |
total timeout in seconds — always set one |
-s / -sS |
silent / silent-but-show-errors |
--data-binary @file.json |
send a file's exact bytes as the body |
--json '{...}' |
shortcut for -d plus Content-Type: application/json and Accept: application/json (curl 7.82 and newer; older versions need the explicit headers) |
A GET with query parameters and an auth header, against our fake API (illustrative — run it yourself in the exercises):
curl -sS "http://127.0.0.1:8377/v1/tickets?status=open&limit=2" \
-H "Authorization: Bearer sk-demo-..." \
-H "Accept: application/json" \
--max-time 10Example output (illustrative — your exact output will differ):
{"data": [{"id": 1042, "subject": "Cannot log in after password reset", "status": "open", "priority": 1}, {"id": 1043, "subject": "Invoice PDF missing VAT line", "status": "open", "priority": 2}]}A POST with a JSON body — note the explicit Content-Type, or the server can't tell JSON from a web form:
curl -sS -X POST "http://127.0.0.1:8377/v1/tickets" \
-H "Authorization: Bearer sk-demo-..." \
-H "Content-Type: application/json" \
-d '{"subject": "VPN drops every afternoon", "priority": 2}' \
-w '\nHTTP %{http_code} in %{time_total}s\n'When debugging, -i shows the response headers with the body — the status line and Content-Type are half the answer (7.1):
curl -i -sS "http://127.0.0.1:8377/v1/tickets/1042" \
-H "Authorization: Bearer sk-demo-..." \
--max-time 10Example output (illustrative — your exact output will differ):
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.14.6
Date: Fri, 06 Nov 2026 14:22:10 GMT
Content-Type: application/json
Content-Length: 94
{"id": 1042, "subject": "Cannot log in after password reset", "status": "open", "priority": 1}For scripts and pipelines, the flags change meaning: -f makes HTTP errors (4xx/5xx) exit non-zero instead of printing the error body — so curl ... && next_step just works — -o saves the body to a file, -L follows redirects, and --max-time caps the whole call:
curl -fsSL --max-time 30 -o ticket.json \
"http://127.0.0.1:8377/v1/tickets/1042" \
-H "Authorization: Bearer sk-demo-..."
# exit code 0 and ticket.json holds the body; exit 22 means an HTTP errorWindows PowerShell note: curl there is an alias for Invoke-WebRequest (different syntax!). Use curl.exe for the real curl, or do these exercises in WSL — 00.1 explains why the path recommends WSL on Windows.
5.2 Browser DevTools: the Network tab#
Every browser has the same instrument: DevTools → Network tab. Reload a page, click any request, and you see the full anatomy from 1.2 — request headers, response headers, timing, payload. Three uses:
- See what your own frontend sends to your backend — the fastest way to answer "is the bug in my JS or my API?"
- Replay a request (right-click → Copy as cURL) to reproduce it in the terminal
- Watch an LLM stream — filter by
Fetch/XHR, open a streaming response, and watchtext/event-streamevents arrive live (00.5 walks through this)
5.3 API clients: Postman, Insomnia, Bruno, Hoppscotch#
GUI API clients save your collections of requests — URL, method, headers, body — with environments for keys. The field as of November 2026 (licences and features move quickly — check each project's own site before choosing for a team):
| Tool | Model | Licence | Offline / local-first | Pricing shape (as of November 2026) |
|---|---|---|---|---|
| Postman | cloud-synced workspaces and collections, huge ecosystem, built-in AI features | proprietary freemium (not open source) | cloud-first; the pricing page lists a Local Vault for secrets but does not describe a full offline mode | Free plan for 1 user (50 AI credits a month on the comparison table; limited monitoring and API calls); Solo $9/month and Team $19 per user/month, both billed annually; Enterprise by quote |
| Insomnia (Kong) | desktop client; per project you choose Local Vault, Git Sync or Cloud Sync, or use the account-free Scratch Pad | Apache-2.0 | yes: Local Vault and Scratch Pad are fully local | Essentials free (unlimited Cloud and Local projects; Git Sync for up to 3 users; 1,000 mock-server requests a month); Pro $12 per user/month; Enterprise $45 per user/month (self-serve up to 50 users) |
| Bruno | collections as plain-text .bru files in your repo; bru run CLI for CI |
MIT | offline-only by design; the README says there are no plans for cloud sync | Open Source edition $0 (public Git providers only); Pro $6, Ultimate $11, Enterprise $18 per user/month, billed annually (private Git providers and further features) |
| Hoppscotch | web app / installable PWA / self-hosted | MIT (community edition; a separate paid enterprise edition exists) | PWA has offline support; self-host keeps data in your own infrastructure | Free community tier and a paid Team/Enterprise tier; the page showed no prices, so check the site |
| Yaak | native desktop client; mirror workspaces to the filesystem for Git or Dropbox | source MIT; prebuilt binaries follow the pricing terms | local-first: data stays on your device unless you export or share it | free for personal use; a licence is required at work: Individual $79/year or $349 one-time, Business $149 per user/year; 30-day commercial trial |
Sources checked in November 2026: Postman pricing, Insomnia pricing and README, Bruno pricing and README, Hoppscotch pricing and repository, Yaak pricing and README. Prices and free-plan limits change often; treat the figures as a snapshot.
All of them import/export cURL and Postman collections — so learning curl transfers everywhere. Bruno's git-native model is the one most aligned with this path's habits (requests reviewed in PRs, next to the code that calls them). You need none of them to finish this module; they're conveniences, not requirements.
5.4 A stdlib Python client: urllib.request#
Python's standard library can make HTTP calls with zero installs — urllib.request for simple calls, http.client for control. Here is the fake tickets API (the same one the exercises use) plus a client that exercises it. Run it: python3 fake_api_demo.py — it binds 127.0.0.1, serves in a thread, makes the calls, and shuts down.
# fake_api_demo.py — stdlib only; run: python3 fake_api_demo.py
import json
import threading
import urllib.error # HTTPError lives here (urllib.request imports it too)
import urllib.request
import http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
TICKETS = [
{"id": 1041, "subject": "Printer offline on floor 3", "status": "closed", "priority": 3},
{"id": 1042, "subject": "Cannot log in after password reset", "status": "open", "priority": 1},
{"id": 1043, "subject": "Invoice PDF missing VAT line", "status": "open", "priority": 2},
{"id": 1044, "subject": "Add dark mode to settings", "status": "open", "priority": 4},
]
NEXT_ID = 1045
KEY = "sk-demo-..." # placeholder, not a real key
class Handler(BaseHTTPRequestHandler):
def _send(self, code, obj=None):
body = b"" if obj is None else json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def _auth(self):
return self.headers.get("Authorization") == f"Bearer {KEY}"
def do_GET(self):
if not self._auth():
return self._send(401, {"error": {"code": "unauthorized", "message": "missing or bad key"}})
url = urlparse(self.path)
qs = parse_qs(url.query)
if url.path == "/v1/tickets":
rows = TICKETS
if "status" in qs:
rows = [t for t in rows if t["status"] == qs["status"][0]]
if "limit" in qs:
rows = rows[: int(qs["limit"][0])]
return self._send(200, {"data": rows})
if url.path.startswith("/v1/tickets/"):
tid = int(url.path.rsplit("/", 1)[1])
for t in TICKETS:
if t["id"] == tid:
return self._send(200, t)
return self._send(404, {"error": {"code": "not_found", "message": f"no ticket {tid}"}})
self._send(404, {"error": {"code": "not_found", "message": "unknown path"}})
def do_POST(self):
global NEXT_ID
if not self._auth():
return self._send(401, {"error": {"code": "unauthorized", "message": "missing or bad key"}})
url = urlparse(self.path)
if url.path != "/v1/tickets":
return self._send(404, {"error": {"code": "not_found", "message": "unknown path"}})
length = int(self.headers.get("Content-Length", 0))
try:
payload = json.loads(self.rfile.read(length))
assert isinstance(payload.get("subject"), str) and payload["subject"].strip()
except (json.JSONDecodeError, AssertionError, AttributeError):
return self._send(422, {"error": {"code": "invalid_body", "message": "subject (non-empty string) is required"}})
ticket = {"id": NEXT_ID, "subject": payload["subject"], "status": "open", "priority": payload.get("priority", 3)}
NEXT_ID += 1
TICKETS.append(ticket)
self._send(201, ticket)
def do_DELETE(self):
if not self._auth():
return self._send(401, {"error": {"code": "unauthorized", "message": "missing or bad key"}})
url = urlparse(self.path)
if url.path.startswith("/v1/tickets/"):
tid = int(url.path.rsplit("/", 1)[1])
for i, t in enumerate(TICKETS):
if t["id"] == tid:
TICKETS.pop(i)
return self._send(204)
self._send(404, {"error": {"code": "not_found", "message": "unknown ticket"}})
def log_message(self, *args): # keep stderr clean: no request log lines
pass
def show(label, status, body):
print(f"--- {label}")
print(f"status: {status}")
print("body:", json.dumps(body, sort_keys=True) if body is not None else "(empty)")
def main():
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{port}"
headers = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"}
# 1) urllib.request — the "batteries included" stdlib client
req = urllib.request.Request(f"{base}/v1/tickets?status=open&limit=2", headers=headers)
with urllib.request.urlopen(req, timeout=5) as r:
show("urllib GET /v1/tickets?status=open&limit=2", r.status, json.loads(r.read()))
# 2) http.client — lower-level, you see the request line you send
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
conn.request("POST", "/v1/tickets", body=json.dumps({"subject": "VPN drops every afternoon", "priority": 2}),
headers=headers)
r = conn.getresponse()
show("http.client POST /v1/tickets", r.status, json.loads(r.read()))
conn.close()
# 3) an error path: DELETE a ticket that does not exist
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
conn.request("DELETE", "/v1/tickets/9999", headers=headers)
r = conn.getresponse()
print(f"--- http.client DELETE /v1/tickets/9999\nstatus: {r.status}\nbody: {r.read().decode()}")
conn.close()
# 4) no key -> 401
try:
urllib.request.urlopen(f"{base}/v1/tickets", timeout=5)
except urllib.error.HTTPError as e:
print(f"--- urllib GET /v1/tickets (no auth header)\nstatus: {e.code}\nbody: {e.read().decode()}")
server.shutdown()
if __name__ == "__main__":
main()--- urllib GET /v1/tickets?status=open&limit=2
status: 200
body: {"data": [{"id": 1042, "priority": 1, "status": "open", "subject": "Cannot log in after password reset"}, {"id": 1043, "priority": 2, "status": "open", "subject": "Invoice PDF missing VAT line"}]}
--- http.client POST /v1/tickets
status: 201
body: {"id": 1045, "priority": 2, "status": "open", "subject": "VPN drops every afternoon"}
--- http.client DELETE /v1/tickets/9999
status: 404
body: {"error": {"code": "not_found", "message": "unknown ticket"}}
--- urllib GET /v1/tickets (no auth header)
status: 401
body: {"error": {"code": "unauthorized", "message": "missing or bad key"}}Four lessons in one screen: urllib.request.Request takes headers as a dict; urlopen raises HTTPError on 4xx/5xx (a feature — it forces you to handle errors); http.client gives you the raw method/path/body control; parse_qs on the server side decodes ?status=open&limit=2 into {"status": ["open"], "limit": ["2"]}.
5.5 Decision table: which HTTP tool when#
| Situation | Reach for | Why |
|---|---|---|
| One-off call, a shell script, CI | curl |
universal, scriptable, every flag visible, no install |
| "What did the browser actually send?" | DevTools Network tab | shows the real request and response — headers, timing, redirects — that your code can't see |
| Exploring an API, sharing a request set with a team | an API client (Bruno, Insomnia, Postman) | collections, environments, history, no code needed |
| Calling an API from Python code | httpx (01B.5) or the provider SDK |
timeouts, retries, pooling, typed errors — urllib can't keep up |
| Learning HTTP with zero dependencies | urllib.request / http.client |
what this lesson's demo used — stdlib only |
| Provider-specific calls (LLM APIs) | the provider SDK | auth headers, retries, streaming, response types handled for you |
And two request-shape decisions the tools don't make for you:
| Question | Default pick | When the other wins |
|---|---|---|
Read with parameters: GET /tickets?status=open&limit=25 vs POST /search with a JSON body |
GET + query string for simple filters — cacheable, bookmarkable, matches REST convention |
complex or nested filters, or a query string that gets long and ugly — some APIs offer POST /search for exactly this reason |
| Where do error details live? | a JSON error body with code/message (+ a request ID) alongside the status |
— a bare 500 with an HTML page is a bug in their API; quote the request ID when reporting it |
Part 6: A raw LLM API call as the worked example#
Time to see everything at once. An LLM call is an ordinary HTTP POST — the same anatomy as our tickets API, pointed at a provider. Here is the same one-line request ("In one sentence, what is an API?") as plain HTTP+JSON for each provider, abridged. No SDK, no key needed to read it — the keys are placeholders; making them for real is 03.1 Part 1, which also shows how to capture exactly what each SDK sends.
OpenAI — Responses API (POST https://api.openai.com/v1/responses):
POST /v1/responses HTTP/1.1
Host: api.openai.com
Authorization: Bearer sk-...
Content-Type: application/json
{"model": "gpt-6-luna", "input": "In one sentence, what is an API?", "max_output_tokens": 200}Response (abridged):
{"id": "resp_...", "object": "response", "status": "completed",
"output": [{"type": "message", "role": "assistant",
"content": [{"type": "output_text", "text": "An API is a contract..."}]}],
"usage": {"input_tokens": 14, "output_tokens": 12, "total_tokens": 26}}Anthropic — Messages API (POST https://api.anthropic.com/v1/messages):
POST /v1/messages HTTP/1.1
Host: api.anthropic.com
Authorization: Bearer sk-ant-...
anthropic-version: 2026-10-21
Content-Type: application/json
{"model": "claude-haiku-5-5", "max_tokens": 200,
"messages": [{"role": "user", "content": "In one sentence, what is an API?"}]}Response (abridged):
{"id": "msg_...", "type": "message", "role": "assistant",
"content": [{"type": "text", "text": "An API is..."}],
"stop_reason": "end_turn", "usage": {"input_tokens": 14, "output_tokens": 12}}Gemini — generateContent (POST https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent):
POST /v1beta/models/gemini-3.8-flash:generateContent HTTP/1.1
Host: generativelanguage.googleapis.com
x-goog-api-key: ...
Content-Type: application/json
{"contents": [{"parts": [{"text": "In one sentence, what is an API?"}]}],
"generationConfig": {"maxOutputTokens": 200}}Response (abridged):
{"candidates": [{"content": {"parts": [{"text": "An API is..."}], "role": "model"},
"finishReason": "STOP"}],
"usageMetadata": {"promptTokenCount": 14, "candidatesTokenCount": 12}}OpenRouter — Chat Completions (POST https://openrouter.ai/api/v1/chat/completions):
POST /api/v1/chat/completions HTTP/1.1
Host: openrouter.ai
Authorization: Bearer sk-or-...
Content-Type: application/json
{"model": "anthropic/claude-haiku-5.5",
"messages": [{"role": "user", "content": "In one sentence, what is an API?"}],
"max_tokens": 200}Response (abridged):
{"id": "gen-...", "object": "chat.completion",
"choices": [{"message": {"role": "assistant", "content": "An API is..."},
"finish_reason": "stop"}],
"usage": {"prompt_tokens": 14, "completion_tokens": 12, "total_tokens": 26}}Read them side by side and the pattern from Part 3 is unmistakable: POST to a resource, Bearer-style auth (Gemini's header is the exception), a JSON body naming the model and input, a JSON body back with the answer nested differently per provider — output[].content[].text, content[].text, candidates[].content.parts[].text, choices[].message.content. The usage block is how you get billed; finish_reason/stop_reason/finishReason tells you why generation ended (length limit vs natural stop — critical when debugging truncated output, 03.4 covers it). One practical detail hides in the 200 limits above: current models can spend part of the output-token cap on internal reasoning before they write the visible answer, so a cap that is ample for one sentence on a plain model can come back truncated or empty on a reasoning model — leave generous headroom and always check the stop reason (02.8 explains reasoning tokens). Responses above are illustrative abridgements; exact field names live in 03.1 and each provider's docs (00.8).
Part 7: Debugging HTTP#
Deep-dive
7.1 Read the status and the body together#
The single most common debugging failure: looking at the status code or the body, never both. 401 with {"error": {"message": "Incorrect API key provided"}} and 401 with an HTML Cloudflare page are different problems. Rule: always print status + headers + body when something fails — curl -i, curl -v, or your client's error object. The body of an error response is where the API tells you what it actually objected to.
7.2 The common failure table#
This is the lesson's failure gallery — the errors you'll actually meet, and what they mean:
| Symptom | Usual cause | First check |
|---|---|---|
401 |
missing/expired/wrong key, wrong auth header name | is the header spelled right? Bearer vs x-api-key? key has no whitespace/newline? |
403 |
authenticated but forbidden — scope, permission, region | error body's code/message; not a key problem |
404 |
wrong path, wrong host, or the resource is gone | compare your URL to the docs character-by-character; check /v1/ prefix |
400 |
malformed JSON, wrong types, missing required field | validate the body against the docs' example; jq . your payload first |
415 |
wrong Content-Type — sent form data or plain text where JSON expected |
-H "Content-Type: application/json" |
422 |
JSON parsed but semantically invalid — bad enum, out-of-range value | read per-field errors in the body |
429 |
rate limited or out of quota | Retry-After header; error body's code distinguishes throttle vs billing |
500/502/503/504 |
their problem — retry with backoff | X-Request-Id/request-id in the response → quote it in the bug report |
JSONDecodeError in your client |
the response wasn't JSON — an HTML error page, a proxy block, an empty body | print response.text before parsing; check Content-Type |
| "works in curl, fails in code" | header casing? missing header the SDK adds? URL-encoded body? | curl -v vs your client's debug log side by side |
| CORS error in browser | browser blocking cross-origin read — the request may still have succeeded | server logs; the API response is invisible to JS but visible in Network tab |
| TLS/cert error | corporate proxy MITM, wrong CA bundle, clock skew | curl -v shows the handshake failure; ask about proxy certs |
7.3 curl -v: reading a trace#
curl -v prints two streams to stderr: lines starting > are what curl sent, < are what the server replied. A condensed real shape:
> POST /v1/messages HTTP/2
> Host: api.anthropic.com
> Authorization: Bearer sk-ant-...
> anthropic-version: 2026-10-21
> Content-Type: application/json
> Content-Length: 152
>
{ [152 bytes data]
< HTTP/2 200
< content-type: application/json
< request-id: req_011CG8Xy...
< x-should-retry: false
<
{ [1234 bytes data]x-should-retry is the provider's explicit retry hint — OpenAI and Anthropic send it (03.8 §4.3); request-id is your support-ticket handle — always log it. When a provider call fails in production, the request ID is the first thing support asks for (03.8 §12).
7.4 Retries: the preview#
Retrying is correct for 408, 429, 5xx and transport errors — wrong for 400, 401, 403, 404, 422 (your request is broken; retrying breaks it identically). The full policy — which errors, how many attempts, what backoff, when the SDK already retries for you — is 01B.9 and, for LLM calls specifically, 03.8 (which errors to retry, x-should-retry, the double-retry trap, timeouts per SDK). The Module 00 rule: every call gets a timeout; every retry gets a cap and a reason.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "HTTP and HTML are the same thing." | HTTP is the protocol for transferring data; HTML is one content type it can carry (text/html). APIs carry application/json. |
| "HTTPS hides the URL completely." | The path, query and headers travel inside the encrypted channel, but the hostname is still visible on the wire (DNS lookup, TLS SNI), and the whole URL still lands in server logs, proxy logs and browser history — which is why secrets never belong in URLs. |
"A 200 means the request worked." |
It means HTTP-level success. The body can still contain "status": "error" — some APIs put business errors inside 200s (03.8 Part 10 covers APIs that do this). Read the body. |
| "GET requests can't have a body / POST can't have a query string." | Both can — the spec doesn't forbid it — but convention and tooling assume GET=query+no body, POST=body. Deviating breaks caches and proxies. |
| "JSON is JavaScript, so it's loose like JS objects." | JSON is stricter than JS: double quotes only, no comments, no trailing commas, no NaN. Python's json is lenient by default (it will read and write NaN) — other languages' parsers are stricter. |
"null and a missing key are the same." |
In JSON they are different states; sloppy APIs blur them. Your code should handle both explicitly. |
| "Base64 is encryption." | It's an encoding — base64 -d reverses it instantly. It protects nothing; HTTPS does the protecting. |
| "Idempotent means 'safe to retry'." | Close but different: idempotent means N identical calls = 1 call's effect. Safe means no side effects at all. PUT is idempotent but not safe. |
| "REST is a protocol like HTTP." | REST is an architectural style — a set of conventions for using HTTP well. There's no REST server software; there's just HTTP used consistently. |
| "An API key in the query string is fine because it's HTTPS." | HTTPS protects it in transit, but the URL is still logged everywhere — server logs, proxies, analytics, browser history. Headers exist for secrets. |
| "CORS protects my API from abuse." | CORS stops browsers reading cross-origin responses; it doesn't stop requests being sent (no preflight for simple requests) and doesn't apply to non-browser clients at all. Auth and rate limits protect APIs. |
"Pagination with page=1,2,3... always gets everything." |
Only if the list is static. Inserts/deletes shift offsets; deep offsets are slow; hardcoded page counts silently truncate. Loop on has_more/cursor. |
| "A timeout is a maximum wait for the whole call." | There are four timeouts (connect, read, write, pool) and they mean different things — a long LLM generation needs a long read timeout but a short connect one. |
| "JSONL is just JSON with extra steps." | It's a sequence of JSON documents, one per line — not one JSON document. Parsers that expect a single value will fail on it. |
| "SSE is a different protocol from HTTP." | SSE is HTTP — a response with Content-Type: text/event-stream that stays open. Same auth, same TLS, same status codes. |
| "Webhooks are guaranteed to arrive exactly once." | They're at-least-once: expect duplicates, verify signatures, dedupe on the event ID. |
Key takeaways#
- HTTP is plain text: start line, headers, blank line, body — same shape for requests and responses.
curl -vand your fake-server exercise show it byte for byte. - Methods carry meaning:
GET/HEAD/OPTIONS/TRACEare safe and idempotent;PUT/DELETEare idempotent but not safe;POSTandCONNECTare neither (PATCH only if you design it so) — which is why retries and idempotency keys matter. - Status codes are contracts: 2xx parse the body, 3xx follow/update, 4xx fix your request (except 408/429), 5xx retry with backoff. Always read status and body together.
- Headers carry the metadata:
Content-Typesays what the body is,Authorizationcarries credentials,Retry-After/X-RateLimit-*pace you, request IDs connect you to support. - URLs are structured: scheme://host:port/path?query#fragment — the fragment never reaches the server; percent-encode anything unusual; never put secrets in URLs.
- JSON is strict: six types, double quotes, no comments/trailing commas/
NaN;json.dumps/loadsmap it to Python dicts/lists/str/int-float/bool/None; JSONL is one object per line for streams and batch files. - REST is a vocabulary: plural-noun resources, methods as verbs, query strings as modifiers, cursor pagination, consistent error envelopes, versioning, idempotency keys, rate limits, webhooks.
- Auth lives in headers: Bearer tokens and API keys in
Authorizationor provider-specific headers — never URLs, never browser code, never logs. - You can call any API by hand:
curlfor quick checks, DevTools Network tab for what your frontend sends,urllib/httpxin Python — and a stdlibhttp.serverfake for offline practice. - LLM calls are ordinary HTTP: same POST+JSON shape on all four providers; streaming is SSE; the full treatment is 03.1 onward.
Where you'll use this in the AI path#
| Skill from this lesson | Used in |
|---|---|
| Reading raw HTTP requests/responses | 03.1 Part 1: An LLM call is an HTTP request — the wire treatment this lesson previews |
| Auth headers per provider | 03.1 §1.2: endpoints and auth headers |
| SSE streaming format | 03.3 §2.1 SSE in one page and §2.2 raw bytes of five streaming APIs |
| JSON bodies, parsing, validation | 03.4 Structured Output — JSON Schema and Pydantic validation of model output |
| JSONL file format | 03.9 §7.1 batch input files; 10A.2 §1.4 eval dataset storage |
| Timeouts, retries, rate limits | 03.8 Errors, rate limits, timeouts and retries; 01B.9 |
| HTTP client in Python | 01B.5 HTTP clients with httpx |
| Webhooks for async jobs | 03.9 §13.6 provider webhooks; 05.9 ingestion pipelines |
| Reading API documentation | 00.8 Reading API Documentation — the very next skill |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| HTTP | The request/response protocol of the web (RFC 9110); plain text: start line, headers, blank line, body |
| HTTPS / TLS | HTTP inside an encrypted TLS connection |
| Method / verb | The request's action word: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE, CONNECT |
| Safe method | A method that changes nothing on the server (GET, HEAD, OPTIONS, TRACE) |
| Idempotent method | A method where N identical calls have the same effect as one (GET, HEAD, OPTIONS, TRACE, PUT, DELETE — POST, CONNECT and PATCH-by-default are not) |
| URL / URI | The address of a resource: scheme://host:port/path?query#fragment |
| Percent-encoding | %XX escaping of characters outside the URL-safe set (RFC 3986) |
| Query string | ?key=value&... parameters after the path — never includes the fragment |
| Status code | The 3-digit response class+detail (200, 404, 429, 503...) |
| Header | A Name: value metadata line in a request or response |
| Content-Type | The media type of a body (application/json, text/event-stream...) |
multipart/form-data |
Body format for mixed/binary content (file uploads); sections split by a boundary parameter, each with its own Content-Type |
| Content negotiation | Client Accept and server Content-Type agreeing on a representation |
| Bearer token | An opaque credential sent as Authorization: Bearer <token> |
| API key | A static secret identifying your account; sent in a header, never a URL |
| Basic auth | Authorization: Basic base64(user:pass) — encoding, not encryption |
| OAuth 2.0 | Delegated authorization: user consents, you get a scoped access token |
| JWT | A signed JSON token (header.payload.signature) used as a bearer credential |
| Signed request | HMAC signature over the request proving the caller holds a secret |
| mTLS | Mutual TLS: both sides present certificates in the handshake; the client certificate is the workload's identity — used by service meshes and cloud platforms |
| REST | An architectural style: resources + HTTP methods, not a protocol |
| Resource / collection | The thing an endpoint names (/tickets/1042) / the plural list (/tickets) |
| Pagination | Fetching a long list in pages — offset, page, or cursor style |
| Cursor | An opaque "continue after this" token for stable pagination |
| Idempotency key | A client-chosen unique ID making a retried POST safe |
| Rate limit | A cap on requests/tokens per time window; 429 + Retry-After enforce it |
| Problem Details | RFC 9457's standard error body (type, title, status, detail, instance) |
| HATEOAS | Hypermedia-driven API discovery — vocabulary only, rarely implemented |
| RPC | Remote procedure call style: invoke a function over the wire |
| GraphQL | One endpoint where the client writes a query for exactly the fields wanted |
| gRPC | Typed RPC over HTTP/2 with Protocol Buffers bodies |
| WebSocket | A persistent bidirectional channel (WS/WSS) for realtime data |
| SSE | Server-Sent Events: an HTTP response of text/event-stream pushed over time |
| Webhook | A provider-initiated HTTP POST to your server on an event |
| JSON | RFC 8259's strict text data format: objects, arrays, strings, numbers, booleans, null |
| JSONL / JSON Lines | One complete JSON value per line — batch files, logs, eval sets |
| JSON Schema | A JSON document describing the allowed shape of other JSON data |
json.dumps / json.loads |
Python: serialize object→JSON string / parse JSON string→object |
jq |
The command-line JSON processor (select, .field, .[]) |
| Timeout (connect/read/write/pool) | The four distinct "give up waiting" limits every call needs |
All terms are also collected in the glossary.
Exercises#
Work through these in order — they build the fake API you will reuse. Create a scratch folder first (mkdir ~/code/api-practice && cd ~/code/api-practice), save fake_api_demo.py from 5.4 there, and run python3 fake_api_demo.py to see it work. Exercises 7, 8 and 15 need the API running standalone: copy fake_api_demo.py to fake_api_server.py, delete everything from def show( to the end of the file, and append the server-only tail shown in the solutions — it prints its address (including the ephemeral port, which is why fake_api_demo.py itself never shows one) and serves until you press Ctrl+C. Keep it running in its own terminal.
- JSON by hand. Write a JSON object describing a support ticket with fields
id(number),subject(string),tags(array of strings),escalated(boolean),assignee(null). Then write the same object as a Python dict and confirmjson.loads(json.dumps(d)) == d. - Spot the invalid JSON. Which of these parse? Fix the ones that don't:
{"a": 1,},{'a': 1},{"a": NaN},{"a": 1} // note,[1, 2, 3]followed by{"x": 1}on the next line (that's JSONL, not JSON). - The NaN trap. Run
json.dumps({"avg": float("nan")})andjson.loads('{"v": NaN}'). Explain why the first output is dangerous and howallow_nan=Falsechanges it. - URL anatomy. Split
https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=XYZinto scheme/host/port/path/query withurllib.parse.urlsplit, and explain why putting the key in?key=is a bad idea even though Google accepts it. - Status codes. For each scenario pick the right code and say whether it's retryable: created a ticket; deleted a ticket; your JSON was malformed; your key is wrong; you're rate-limited; the server crashed.
- Method properties. Which of GET/POST/PUT/PATCH/DELETE are safe? Which are idempotent? Why is retrying a POST risky and what do idempotency keys solve?
- Fake API, by hand. With the fake server running, call
GET /v1/tickets?status=openwithcurl -i(orhttp.clientin Python). Identify the start line, three headers and the body in the response. - Write the request by hand. Using the raw-socket technique from 1.10, send a
POST /v1/ticketswithContent-Type: application/jsonand body{"subject": "Test ticket", "priority": 5}to the fake API. Print the raw response and find the status line. - JSONL. Write a 3-line
.jsonlfile of eval cases, read it back line by line withjson.loads, and explain why this format suits batch APIs. - jq. Given
sample.jsonfrom the lesson, usejqto list only open tickets' subjects, count them, and extract the first ticket's id. - Provider headers. From memory, write the auth header and one required extra header for each of: OpenAI Responses, Anthropic Messages, Gemini generateContent, OpenRouter Chat Completions. Then verify against 03.1 §1.2.
- Error body design. Design a consistent error JSON envelope for the tickets API (fields:
error.code,error.message,error.request_id). Write the response the API should return for a 422 and explain whycodemust be stable whilemessagecan change. - Debugging. A classmate's
urllibcall getsHTTPError: 401. List the three most likely causes in order and the exact command/print that would distinguish them. - SSE reading. Given the SSE stream in 3.10, write the Python loop that reads lines and prints only the
contentdeltas. (Hint:for line in response.iter_lines()in httpx, orfor line in r:with urllib — 01B.5 and 03.3 go deeper.) - Where it breaks. Call
GET /v1/tickets/abc(non-numeric id) on the fake API. What happens? Read the server code, predict, then verify — and explain why a production API should return400/422rather than crash.
Solutions
Setup for exercises 7, 8 and 15 — the standalone server. Copy fake_api_demo.py to fake_api_server.py, delete everything from def show( to the end of the file, and append:
if __name__ == "__main__":
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
base = f"http://127.0.0.1:{server.server_address[1]}"
print(f"serving on {base} — Ctrl+C to stop", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
server.server_close()Run python3 fake_api_server.py in its own terminal; it prints e.g. serving on http://127.0.0.1:62796 — Ctrl+C to stop. Use that base URL — with your printed port — in exercises 7, 8 and 15. The client imports (urllib.request, http.client) stay unused; harmless.
1. JSON:
{"id": 1042, "subject": "Cannot log in after reset", "tags": ["login", "urgent"], "escalated": false, "assignee": null}Python: d = {"id": 1042, "subject": "Cannot log in after reset", "tags": ["login", "urgent"], "escalated": False, "assignee": None} and json.loads(json.dumps(d)) == d is True — JSON false→False, null→None, arrays→lists.
2. Parses: [1, 2, 3] alone. Fails: {"a": 1,} (trailing comma), {'a': 1} (single quotes), {"a": NaN} (bare NaN — Python accepts it actually! json.loads('{"a": NaN}') works in Python but is invalid strict JSON — the strict answer is "Python parses it, JavaScript doesn't"), {"a": 1} // note (extra data). Two documents on separate lines = JSONL.
3. json.dumps({"avg": float("nan")}) → {"avg": NaN} — invalid JSON that strict parsers reject; the receiving service can't tell it was a missing-data problem. json.loads('{"v": NaN}') → {'v': nan} — Python is lenient on reads. allow_nan=False makes dumps raise ValueError instead of emitting invalid JSON.
4.
>>> u = urllib.parse.urlsplit("https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent?key=XYZ")
>>> u.scheme, u.hostname, u.port, u.path, u.query
('https', 'generativelanguage.googleapis.com', None, '/v1beta/models/gemini-3.8-flash:generateContent', 'key=XYZ')port is None because no :port was written — 443 is implied by https. ?key= is a bad idea because URLs are recorded in server access logs, proxy logs, browser history and Referer headers; Google merely tolerates it, which is why x-goog-api-key exists as the header form.
5.
| Scenario | Code | Retryable? |
|---|---|---|
| created a ticket | 201 Created |
not blindly — each retry would create another ticket; safe only behind an idempotency key |
| deleted a ticket | 204 No Content (or 200) |
yes — DELETE is idempotent |
| malformed JSON | 400 Bad Request |
no — fix the request first |
| wrong key | 401 Unauthorized |
no — fix credentials first |
| rate-limited | 429 Too Many Requests |
yes — after Retry-After / backoff |
| server crashed | 500 Internal Server Error |
yes — bounded retries with backoff |
6. Safe: GET, HEAD, OPTIONS, TRACE. Idempotent: GET, HEAD, OPTIONS, TRACE, PUT, DELETE. PATCH is not required to be idempotent (though {"status": "closed"} applied twice gives the same result — design yours to be). POST and CONNECT are neither. Retrying a POST is risky because every call can create a new resource or bill a new generation; an idempotency key lets the server recognise a retry and return the first result instead of acting again.
7. (illustrative) HTTP/1.0 200 OK + headers (Content-Type: application/json, Content-Length, Server, Date) + body {"data": [{"id": 1042, ...}, {"id": 1043, ...}, {"id": 1044, ...}]} — three open tickets. Start line = first line; headers = the Name: value lines; blank line; then the JSON body.
8. The response start line is HTTP/1.0 201 Created (BaseHTTPRequestHandler defaults to HTTP/1.0 responses) with the created ticket {"id": 1045, "subject": "Test ticket", "status": "open", "priority": 5} as the body.
9. Write three lines like cases.jsonl above, then for line in open("cases.jsonl", encoding="utf-8"): obj = json.loads(line) and use obj["input"]/obj["expected"]. Batch APIs prefer JSONL because each line is an independent request — the provider can shard, stream and retry per line, and one malformed line can't poison the whole file.
10.
$ jq -r '.data[] | select(.status == "open") | .subject' sample.json
Cannot log in
Invoice missing VAT
$ jq '[.data[] | select(.status == "open")] | length' sample.json
2
$ jq -r '.data[0].id' sample.json
1042(-r drops the quotes on strings; wrapping the filter in [...] turns the stream into an array so length counts it.)
11. OpenAI: Authorization: Bearer <key>. Anthropic: Authorization: Bearer <key> + anthropic-version: 2026-10-21. Gemini: x-goog-api-key: <key>. OpenRouter: Authorization: Bearer <key>.
12. A model envelope for a 422 on POST /v1/tickets:
{"error": {"code": "invalid_priority", "message": "priority must be an integer between 1 and 5", "request_id": "req_9f2c41ab"}}code is a stable machine-readable enum clients branch on (if err["error"]["code"] == "invalid_priority"); message is for humans and may be reworded, localised or made more specific per instance; request_id ties the response to your server logs. This is the §3.7 rule — one documented envelope, stable code, human message — and a step toward RFC 9457 Problem Details.
13. Most likely first: (1) the Authorization header is missing entirely — the headers= argument was forgotten or the variable holding it is empty; (2) wrong scheme or header name — Bearer vs x-api-key, or a provider-specific header like x-goog-api-key; (3) the key value itself is wrong, expired, or carries stray whitespace/a trailing newline from .env. Distinguish them: print(e.read().decode()) shows the provider's error body (it usually says which); print(req.headers) or curl -v shows exactly what was sent; print(repr(os.environ.get("TICKETS_API_KEY"))) reveals hidden whitespace.
14. This runs for real — stdlib only, against a tiny SSE server on 127.0.0.1 (save as sse_demo.py, run python3 sse_demo.py):
# sse_demo.py — stdlib only; run: python3 sse_demo.py
import json
import threading
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
# A canned token stream, exactly the shape OpenAI sends (abridged).
EVENTS = [
{"id": "chatcmpl-x", "choices": [{"delta": {"role": "assistant"}, "index": 0}]},
{"id": "chatcmpl-x", "choices": [{"delta": {"content": "Hello"}, "index": 0}]},
{"id": "chatcmpl-x", "choices": [{"delta": {"content": " there"}, "index": 0}]},
{"id": "chatcmpl-x", "choices": [{"delta": {"content": "!"}, "index": 0}]},
{"id": "chatcmpl-x", "choices": [{"delta": {}, "finish_reason": "stop", "index": 0}]},
]
class SSEHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close") # the demo ends the stream
self.end_headers()
for e in EVENTS:
self.wfile.write(f"data: {json.dumps(e)}\n\n".encode())
self.wfile.flush()
self.wfile.write(b"data: [DONE]\n\n")
self.wfile.flush()
self.close_connection = True
def log_message(self, *args):
pass
def main():
server = ThreadingHTTPServer(("127.0.0.1", 0), SSEHandler)
port = server.server_address[1]
threading.Thread(target=server.serve_forever, daemon=True).start()
with urllib.request.urlopen(f"http://127.0.0.1:{port}/stream", timeout=5) as r:
print("Content-Type:", r.headers["Content-Type"])
for raw in r: # yields lines as they arrive
line = raw.decode().strip()
if not line.startswith("data:"):
continue
payload = line[len("data:"):].strip()
if payload == "[DONE]":
print("\n[DONE]")
break
event = json.loads(payload)
delta = event["choices"][0].get("delta", {})
if "content" in delta:
print(delta["content"], end="", flush=True)
server.shutdown()
if __name__ == "__main__":
main()Content-Type: text/event-stream
Hello there!
[DONE]The loop is the whole skill: read lines as they arrive (for raw in r works because the response object yields lines; httpx's iter_lines() does the same), keep only data: lines, skip [DONE], json.loads each payload, and print choices[0].delta.content when present. Role-only and finish events have no content key — the .get("delta", {}) + "content" in delta guard skips them. With httpx the same loop is for line in r.iter_lines(): inside with httpx.stream(...) as r: — 01B.5 and 03.3 go deeper.
15. The handler does int(url.path.rsplit("/", 1)[1]) → ValueError → the server drops the connection; the client sees an empty reply / RemoteDisconnected. A production API validates path params and returns 400 {"error": {"code": "invalid_id", ...}}. Lesson: your fake server is deliberately minimal — real frameworks (FastAPI, 01B.7) validate types automatically.
Check yourself#
- Name the four parts of an HTTP request and the four parts of a response.Request: start line (method + target + version), headers, blank line, body. Response: status line, headers, blank line, body.
- Which HTTP methods are safe? Which are idempotent? Why does that make
POSTthe risky one to retry?Safe: GET, HEAD, OPTIONS, TRACE. Idempotent: GET, HEAD, OPTIONS, TRACE, PUT, DELETE. POST, CONNECT and PATCH (unless designed so) are not — a POST can create a new resource or bill a new generation on every call. - What does the fragment (
#section) in a URL do — and why is it never sent to the server?It's a client-side anchor (browser scroll position); the HTTP request target excludes it entirely. - A client sends
GET /v1/tickets?api_key=sk-.... What's wrong with this, even over HTTPS?URLs get logged in server/proxy/browser history; credentials belong in headers. - Your API call returns
HTTP/1.1 204. Should you try to parse the body as JSON? Why or why not?No — 204 means "no content"; there is no body to parse. - What's the difference between
401and403?401 = unauthenticated (who are you?); 403 = authenticated but not authorised (I know you, and no). - JSON looks like Python dicts. Name three things JSON forbids that Python allows.Comments, trailing commas, single-quoted strings/keys,
NaN/Infinity, unquoted keys, hex numbers. - Why does
json.dumps({"x": float("nan")})produce output that other languages' parsers reject?Python's defaultallow_nan=Trueemits the bare tokenNaN, which RFC 8259 doesn't define — strict parsers (JSJSON.parse, Go, providers) reject it. - What's the difference between a
.jsonfile and a.jsonlfile, and why do batch APIs prefer JSONL?.jsonis one document;.jsonlis one JSON value per line — streamable, appendable, failure-local. Batch APIs process millions of independent requests. - What are the three pagination styles, and which is the modern default for APIs?Offset/limit, page numbers, cursor/keyset. Cursor is the modern default (stable under inserts, fast at depth).
- What is an idempotency key, and why don't LLM inference APIs offer one?A client-generated unique ID letting a server return the first result on retry instead of acting twice. LLM calls are POSTs that generate (and bill) fresh output each time — there's no "first result" to return.
- Name the auth header each of these uses: OpenAI, Anthropic Messages, Gemini generateContent, OpenRouter.OpenAI
Authorization: Bearer; AnthropicAuthorization: Bearer(or legacyx-api-key) +anthropic-version; Geminix-goog-api-key; OpenRouterAuthorization: Bearer. - What does
Content-Type: text/event-streamsignal, and which LLM feature uses it?An SSE stream — server pushes events over one HTTP response; it's how LLM streaming works. - A
curlcall returns429withRetry-After: 30. What should your code do?Wait ~30 seconds (honourRetry-After), then retry — with a cap and backoff, not a tight loop. - Why must webhook handlers verify signatures and deduplicate events?Webhooks are at-least-once (duplicates happen) and anyone who learns your URL can POST fake events — the signature proves the sender holds the shared secret.
Further resources#
- RFC 9110 — HTTP Semantics (rfc-editor.org/rfc/rfc9110): the authoritative spec for methods, status codes, headers. Dense but definitive — read §9 (methods) and §15 (status codes) once.
- RFC 8259 — JSON (rfc-editor.org/rfc/rfc8259): the JSON spec in four pages.
- RFC 9457 — Problem Details for HTTP APIs (rfc-editor.org/rfc/rfc9457): the standard error-body format.
- MDN HTTP overview (developer.mozilla.org/en-US/docs/Web/HTTP): the friendlier companion to the RFCs — status code reference, headers, methods.
- Python docs:
urllib.requestandhttp.server(docs.python.org/3/library/urllib.request.html, http.server): the stdlib you used in this lesson. jqmanual (jqlang.github.io/jq/manual): the JSON query language used in 2.7.- Fielding's dissertation ("Architectural Styles and the Design of Network-based Software Architectures", 2000): where REST and HATEOAS come from — read Chapter 5 when you're curious.
- curl documentation (curl.se/docs): every flag in 5.1 and far more.
- JSON Schema (json-schema.org): the spec behind 2.9 and LLM structured output.
- OpenAPI Specification (spec.openapis.org): the standard machine-readable API description — version 3.2.x as of November 2026; 00.8 teaches you to read it.
← 00.5 — How Web Apps Work: Client, Server and Database | Module 00 overview | 00.7 — SQL Basics with SQLite →