Chapter 2 · API Design and API Clients
HTTP in Depth: Idempotency, Caching and Auth
- Page 4 of 22
- 29 min read
In the beginner tutorial you sent requests, read status codes and called APIs with API keys and bearer tokens. That is enough to use an API. It is not enough to design or operate one. Why can a client safely retry one request but not another? Why does a mobile app in Dhaka re-download a 2 MB model card on every launch when the server could say "nothing changed" in 200 bytes? Why does a 401 not mean the same as a 403, and what really happens when an app says "Sign in with Google"? These questions come back every time you put an AI model behind an API, because model calls are slow, expensive and often retried.
This page answers them with a small FastAPI app you run yourself and poke with curl: methods and idempotency, status codes, content negotiation, caching with ETag and 304, authentication and authorisation, API keys against bearer tokens, and the OAuth 2.0 / OpenID Connect flows, including a tiny working authorization server that checks PKCE.
What you will learn
- Which HTTP methods are safe and which are idempotent, why that decides what a client may retry, and when to choose PUT or PATCH.
- The status codes that matter in practice, and how a client should react to each.
- Content negotiation with
Accept, and caching withCache-Control,ETag,If-None-Matchand304, implemented in FastAPI. - Authentication against authorisation (401 against 403), API keys against bearer tokens, and scopes.
- OAuth 2.0 and OpenID Connect: authorization code with PKCE, client credentials, and why the password grant must not be used.
One request, end to end
Everything on this page happens inside one request and its response. Keep this picture in mind; each section zooms into one arrow.
client server
| 1. DNS lookup, TCP connect, TLS handshake |
|------------------------------------------->|
| 2. METHOD /path?query HTTP/1.1 | method: what to do
| Host, Accept, Authorization, If-None-Match headers: who, which format, which version
| body (JSON) |
|------------------------------------------->|
| 3. authenticate (who?) | 401 if unknown
| 4. authorise (allowed?) | 403 if not allowed
| 5. validate + run | 400/404/409/422
| 6. status, headers (ETag, Cache-Control), |
| body |
|<-------------------------------------------|
| 7. client caches, parses, retries or fails |The lab app
Create a project and four small files. Read them quickly now: each part is explained in the section where we use it. main.py holds the model resources, caching.py the negotiated and cached read endpoints, auth.py the 401/403 logic, and oauth.py a toy authorization server (a real one, such as Keycloak, Auth0 or your cloud's identity service, is a product you never write yourself; this one only exists so that you can watch the protocol).
mkdir -p ~/projects/http-lab
cd ~/projects/http-lab
uv init --bare -q
uv add -q "fastapi[standard]"
# with pip instead:
# python -m venv .venv && source .venv/bin/activate
# pip install -q "fastapi[standard]"
lspyproject.toml
uv.lock# file: main.py
from typing import Annotated
from fastapi import FastAPI, Header, HTTPException, Response
from pydantic import BaseModel
import auth
import caching
import oauth
from caching import MODELS, etag_of, model_body
app = FastAPI(title="HTTP lab")
app.include_router(caching.router)
app.include_router(auth.router)
app.include_router(oauth.router)
JOBS = {"count": 0}
class ModelIn(BaseModel):
dim: int
status: str
class ModelPatch(BaseModel):
dim: int | None = None
status: str | None = None
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/jobs", status_code=201)
def create_job(response: Response):
JOBS["count"] += 1 # every call creates something new
response.headers["Location"] = f"/jobs/{JOBS['count']}"
return {"job": JOBS["count"]}
@app.put("/models/{name}")
def put_model(
name: str,
item: ModelIn,
response: Response,
if_match: Annotated[str | None, Header()] = None,
):
created = name not in MODELS
if if_match is not None and (created or if_match != etag_of(model_body(name), "json")):
raise HTTPException(412, "the model changed since you read it")
MODELS[name] = item.model_dump() # replace the whole resource
response.status_code = 201 if created else 200
return model_body(name)
@app.patch("/models/{name}")
def patch_model(name: str, item: ModelPatch):
if name not in MODELS:
raise HTTPException(404, "model not found")
MODELS[name].update(item.model_dump(exclude_unset=True)) # change only what was sent
return model_body(name)
@app.delete("/models/{name}", status_code=204)
def delete_model(name: str):
if MODELS.pop(name, None) is None:
raise HTTPException(404, "model not found")# file: caching.py
import hashlib
import json
from typing import Annotated
from fastapi import APIRouter, Header, HTTPException, Request, Response
from fastapi.responses import JSONResponse, PlainTextResponse
router = APIRouter()
MODELS = {"embed-small": {"dim": 384, "status": "active"}}
def model_body(name: str) -> dict:
return {"name": name, **MODELS[name]}
def etag_of(body: dict, fmt: str) -> str:
"""A strong validator: changes whenever the representation changes."""
digest = hashlib.sha256(json.dumps([fmt, body], sort_keys=True).encode()).hexdigest()
return f'"{digest[:12]}"'
@router.get("/models/{name}")
def get_model(name: str, request: Request, accept: Annotated[str, Header()] = "*/*"):
if name not in MODELS:
raise HTTPException(404, "model not found")
if "application/json" in accept or "*/*" in accept:
fmt = "json"
elif "text/plain" in accept:
fmt = "text"
else:
raise HTTPException(406, "available: application/json, text/plain")
body = model_body(name)
headers = {"ETag": etag_of(body, fmt), "Cache-Control": "no-cache", "Vary": "Accept"}
if request.headers.get("if-none-match") == headers["ETag"]:
return Response(status_code=304, headers=headers)
if fmt == "text":
return PlainTextResponse("\n".join(f"{k}={v}" for k, v in body.items()), headers=headers)
return JSONResponse(body, headers=headers)
@router.get("/catalog")
def catalog(response: Response):
response.headers["Cache-Control"] = "public, max-age=300"
return {"models": sorted(MODELS)}# file: auth.py
from typing import Annotated
from fastapi import APIRouter, Depends, Header, HTTPException
from caching import MODELS, model_body
router = APIRouter(prefix="/secure")
# Bearer tokens (the OAuth server in oauth.py adds more) and API keys for services.
TOKENS = {"tok-read": {"sub": "nadia", "scopes": ["models:read"]}}
API_KEYS = {"key-ingest-1": "ingest-service"}
def bearer(authorization: Annotated[str | None, Header()] = None) -> dict:
"""Authentication: who is calling? Failure is 401 and says how to authenticate."""
if authorization is None or not authorization.startswith("Bearer "):
raise HTTPException(401, "missing bearer token", headers={"WWW-Authenticate": "Bearer"})
token = TOKENS.get(authorization.removeprefix("Bearer "))
if token is None:
raise HTTPException(401, "invalid token", headers={"WWW-Authenticate": 'Bearer error="invalid_token"'})
return token
def need(scope: str):
"""Authorisation: is this caller allowed to do this? Failure is 403."""
def check(token: Annotated[dict, Depends(bearer)]) -> dict:
if scope not in token["scopes"]:
raise HTTPException(403, f"requires scope {scope}")
return token
return check
@router.get("/models")
def list_models(token: Annotated[dict, Depends(need("models:read"))]):
return {"user": token["sub"], "models": sorted(MODELS)}
@router.post("/models/{name}/retire")
def retire(name: str, token: Annotated[dict, Depends(need("models:write"))]):
if name not in MODELS:
raise HTTPException(404, "model not found")
MODELS[name]["status"] = "retired"
return {**model_body(name), "by": token["sub"]}
@router.post("/ingest")
def ingest(x_api_key: Annotated[str | None, Header()] = None):
service = API_KEYS.get(x_api_key or "")
if service is None:
raise HTTPException(401, "invalid or missing API key")
return {"accepted": True, "service": service}# file: oauth.py
import hashlib
import itertools
from base64 import urlsafe_b64encode
from typing import Annotated
from fastapi import APIRouter, Form, HTTPException
from fastapi.responses import JSONResponse, RedirectResponse
from auth import TOKENS
router = APIRouter(prefix="/oauth")
CLIENTS = {
# a confidential client (a backend job) can keep a secret
"batch-job": {"secret": "batch-secret", "scopes": ["models:read", "models:write"]},
# a public client (a browser or mobile app) cannot: it relies on PKCE instead
"web-app": {"secret": None, "redirect_uri": "http://localhost:3000/callback", "scopes": ["models:read"]},
}
CODES: dict[str, dict] = {}
code_numbers = itertools.count(1)
token_numbers = itertools.count(2) # tok-read is token 1
def s256(verifier: str) -> str:
digest = hashlib.sha256(verifier.encode()).digest()
return urlsafe_b64encode(digest).rstrip(b"=").decode()
def issue(sub: str, scopes: list[str]) -> JSONResponse:
token = f"tok-{next(token_numbers)}"
TOKENS[token] = {"sub": sub, "scopes": scopes}
body = {"access_token": token, "token_type": "Bearer", "expires_in": 600, "scope": " ".join(scopes)}
return JSONResponse(body, headers={"Cache-Control": "no-store"})
def error(code: str, status: int = 400) -> JSONResponse:
return JSONResponse({"error": code}, status_code=status, headers={"Cache-Control": "no-store"})
@router.get("/authorize")
def authorize(
response_type: str, client_id: str, redirect_uri: str, scope: str, state: str,
code_challenge: str, code_challenge_method: str,
):
"""Normally a login + consent page. Here Nadia has already said yes."""
client = CLIENTS.get(client_id)
if client is None or client.get("redirect_uri") != redirect_uri:
raise HTTPException(400, "unknown client or unregistered redirect_uri") # never redirect there
if response_type != "code" or code_challenge_method != "S256":
return RedirectResponse(f"{redirect_uri}?error=invalid_request&state={state}", status_code=302)
code = f"code-{next(code_numbers)}"
CODES[code] = {"client_id": client_id, "challenge": code_challenge, "scopes": scope.split(), "sub": "nadia"}
return RedirectResponse(f"{redirect_uri}?code={code}&state={state}", status_code=302)
@router.post("/token")
def token(
grant_type: Annotated[str, Form()],
client_id: Annotated[str, Form()],
client_secret: Annotated[str | None, Form()] = None,
scope: Annotated[str, Form()] = "",
code: Annotated[str | None, Form()] = None,
code_verifier: Annotated[str | None, Form()] = None,
):
client = CLIENTS.get(client_id)
if client is None:
return error("invalid_client", 401)
if grant_type == "client_credentials":
if client["secret"] is None or client["secret"] != client_secret:
return error("invalid_client", 401)
wanted = scope.split() or client["scopes"]
if not set(wanted) <= set(client["scopes"]):
return error("invalid_scope")
return issue(client_id, wanted)
if grant_type == "authorization_code":
grant = CODES.pop(code or "", None) # a code works once
if grant is None or grant["client_id"] != client_id or s256(code_verifier or "") != grant["challenge"]:
return error("invalid_grant")
return issue(grant["sub"], grant["scopes"])
return error("unsupported_grant_type")Start it in the background, output redirected, and wait until it answers. Requests below use a tiny wrapper script, ./call, that runs curl -s and appends the status code on the same line as the body.
uv run fastapi run main.py --port 8000 > server.log 2>&1 &
export SERVER_PID=$!
curl -s --retry 20 --retry-connrefused --retry-delay 0 http://localhost:8000/health
cat > call <<'EOF'
#!/bin/sh
exec curl -s -w ' -> HTTP %{http_code}\n' "$@"
EOF
chmod +x call
export BASE=http://localhost:8000{"status":"ok"}Safe and idempotent methods
Two properties of HTTP methods decide what clients, proxies, browsers and retry libraries may do without asking you.
- Safe: the request does not change anything on the server (it only reads). Safe requests can be prefetched, cached and repeated freely.
- Idempotent: sending the request once or ten times leaves the server in the same state. Idempotent requests can be retried after a timeout without fear, because you do not know whether the first one arrived.
| Method | Meaning | Safe | Idempotent | Retry after a timeout? |
|---|---|---|---|---|
GET, HEAD, OPTIONS | Read | Yes | Yes | Yes |
PUT | Replace a resource with this representation | No | Yes | Yes |
DELETE | Remove a resource | No | Yes | Yes |
POST | Create something / run an action | No | No | Only with an idempotency key (next page) |
PATCH | Change part of a resource | No | Depends on the patch | Only if you know the patch is idempotent |
"Idempotent" is about the server state, not the response: the second DELETE may answer 404, but the model is gone either way. See it live. First POST three times, then PUT twice:
./call -X POST $BASE/jobs
./call -X POST $BASE/jobs
./call -X POST $BASE/jobs
echo "--- PUT twice"
./call -X PUT $BASE/models/embed-large -H 'Content-Type: application/json' -d '{"dim": 1024, "status": "active"}'
./call -X PUT $BASE/models/embed-large -H 'Content-Type: application/json' -d '{"dim": 1024, "status": "active"}'{"job":1} -> HTTP 201
{"job":2} -> HTTP 201
{"job":3} -> HTTP 201
--- PUT twice
{"name":"embed-large","dim":1024,"status":"active"} -> HTTP 201
{"name":"embed-large","dim":1024,"status":"active"} -> HTTP 200Three POSTs made three jobs. If your client timed out on the second and retried, you would not know whether you now have two or three jobs, and for "start a fine-tuning run" or "charge the card" that is a real bug. The two PUTs left a single embed-large: the first created it (201), the second replaced it with identical content (200). That is why HTTP libraries retry GET and PUT automatically but never POST.
PUT or PATCH?
PUT sends the complete new resource, so a missing field is an error (or reset to default). PATCH sends only the change.
./call -X PUT $BASE/models/embed-large -H 'Content-Type: application/json' -d '{"status": "retired"}'
./call -X PATCH $BASE/models/embed-large -H 'Content-Type: application/json' -d '{"status": "retired"}'
./call -X DELETE $BASE/models/embed-large
./call -X DELETE $BASE/models/embed-large{"detail":[{"type":"missing","loc":["body","dim"],"msg":"Field required","input":{"status":"retired"}}]} -> HTTP 422
{"name":"embed-large","dim":1024,"status":"retired"} -> HTTP 200
-> HTTP 204
{"detail":"model not found"} -> HTTP 404The PUT without dim was refused with 422; the PATCH with just status worked. The first DELETE answered 204 (success, no body); the second 404, yet the end state is identical, so DELETE is idempotent. A PATCH such as {"status": "retired"} is idempotent; a patch like "add 10 to quota" is not, and a client must not retry it blindly. A standard format for patches is JSON Patch (RFC 6902); many APIs simply use a JSON object of the changed fields, as we do (the "merge patch" style).
Status codes in practice
You know the families from the beginner tutorial. In practice, what matters is what the client does next:
| Code | Use it for | The client should… |
|---|---|---|
200, 201 + Location, 204 | OK / created / done with no body | Use the result |
202 | Accepted, not finished (long job) | Poll the status URL (next page) |
301, 308 | Moved permanently | Follow, update stored URLs |
304 | Not modified (conditional GET) | Use its cached copy |
400, 422 | Malformed request / valid JSON but invalid data | Fix the request; never retry unchanged |
401 | Not authenticated (no or bad credentials) | Log in or refresh the token, then retry once |
403 | Authenticated but not allowed | Do not retry; ask for access |
404, 410 | Does not exist / gone for good | Do not retry |
405, 406, 415 | Wrong method / cannot produce the Accept format / unsupported body type | Fix the request |
409, 412 | Conflict with current state / precondition (If-Match) failed | Re-read, merge, try again |
429 | Too many requests | Wait for Retry-After, then retry |
500 | Server bug | Retry idempotent calls cautiously |
502, 503, 504 | Bad gateway / unavailable / gateway timeout | Retry with backoff (idempotent calls) |
Three of these you can trigger right now. Note the Allow header that a 405 must send:
./call $BASE/models/does-not-exist
curl -s -i -X DELETE $BASE/health | tr -d '\r' | grep -i -E '^(HTTP|allow)'
./call -X PUT $BASE/models/x -H 'Content-Type: application/json' -d '{"dim": "big", "status": "active"}'{"detail":"model not found"} -> HTTP 404
HTTP/1.1 405 Method Not Allowed
allow: GET
{"detail":[{"type":"int_parsing","loc":["body","dim"],"msg":"Input should be a valid integer, unable to parse string as an integer","input":"big"}]} -> HTTP 422A good API uses the code to say who is at fault and whether trying again can help: 4xx means "you must change something", 5xx means "I failed, maybe try later". Returning 200 with {"error": ...} in the body breaks every client, proxy and monitoring dashboard that trusts the status line.
Content negotiation
One URL, several representations. The client states what it can read with Accept; the server picks one and labels it with Content-Type, or answers 406 Not Acceptable. The Vary: Accept header tells caches that the response depends on that header. The same idea applies to Accept-Language (Bangla or English) and Accept-Encoding (gzip, handled for you by servers and clients).
./call $BASE/models/embed-small
./call -H 'Accept: text/plain' $BASE/models/embed-small
./call -H 'Accept: image/png' $BASE/models/embed-small
curl -s -i -H 'Accept: text/plain' $BASE/models/embed-small | tr -d '\r' | grep -i -E '^(content-type|vary)'{"name":"embed-small","dim":384,"status":"active"} -> HTTP 200
name=embed-small
dim=384
status=active -> HTTP 200
{"detail":"available: application/json, text/plain"} -> HTTP 406
vary: Accept
content-type: text/plain; charset=utf-8In the code, get_model looks at Accept, chooses a format, and refuses the rest. The request body has the mirror image: Content-Type says what the client sends, and a server answers 415 Unsupported Media Type for a body it cannot parse. Real servers also honour quality values (Accept: text/plain;q=0.5, application/json); frameworks and libraries implement that for you, so we kept the logic crude on purpose. Many APIs also negotiate a version this way (Accept: application/vnd.example.v2+json); the next page compares versioning strategies.
Caching with Cache-Control, ETag and 304
The fastest request is the one that is never sent, and the cheapest response is a tiny one. HTTP has two mechanisms, and good APIs use both.
- Freshness (
Cache-Control: max-age=…): the server says "this stays valid for N seconds"; clients and shared caches reuse it with no request at all. - Validation (
ETag+If-None-Match): after the copy is stale, the client asks "I have version"abc"; is it still current?" The server answers304 Not Modifiedwith no body, or a full200with the new version.
Look at what our endpoints send:
curl -s -i $BASE/models/embed-small | tr -d '\r' | grep -i -E '^(HTTP|etag|cache-control)'
curl -s -i $BASE/catalog | tr -d '\r' | grep -i -E '^(HTTP|etag|cache-control)'HTTP/1.1 200 OK
etag: "3c66bb0b1a1d"
cache-control: no-cache
HTTP/1.1 200 OK
cache-control: public, max-age=300The catalog may be reused for five minutes (public, max-age=300) without asking again. The model card says no-cache, which does not mean "do not cache": it means "you may store it, but you must validate with me before using it". Now the conditional request:
ETAG=$(curl -s -i $BASE/models/embed-small | tr -d '\r' | grep -i '^etag:' | cut -d' ' -f2)
echo "validator: $ETAG"
curl -s -o /dev/null -w 'first fetch: HTTP %{http_code}, %{size_download} bytes\n' $BASE/models/embed-small
curl -s -o /dev/null -w 'revalidation: HTTP %{http_code}, %{size_download} bytes\n' -H "If-None-Match: $ETAG" $BASE/models/embed-small
./call -X PATCH $BASE/models/embed-small -H 'Content-Type: application/json' -d '{"dim": 768}'
curl -s -o /dev/null -w 'after change: HTTP %{http_code}, %{size_download} bytes\n' -H "If-None-Match: $ETAG" $BASE/models/embed-smallvalidator: "3c66bb0b1a1d"
first fetch: HTTP 200, 50 bytes
revalidation: HTTP 304, 0 bytes
{"name":"embed-small","dim":768,"status":"active"} -> HTTP 200
after change: HTTP 200, 50 bytesThe ETag is a fingerprint of the representation (here a hash; in a database app it might be a row version). The client keeps the body and the ETag; on the next use it sends If-None-Match. Unchanged: 304, zero body bytes, no JSON parsing. Changed: 200 and the new body. In FastAPI you write that logic yourself, as in get_model (some frameworks and CDNs generate ETags for you). Notes:
| Directive / header | Meaning |
|---|---|
max-age=N | Fresh for N seconds; no request needed |
no-cache | Store it, but revalidate every time |
no-store | Never store: use for tokens, personal data, per-user LLM answers |
public / private | Shared caches (CDN) may store / only the user's own browser may store |
s-maxage=N | Like max-age but for shared caches only |
immutable | Never changes: good for files named by their hash (model-3f9a.bin) |
stale-while-revalidate=N | Serve the stale copy while refreshing in the background |
Vary: Accept, Authorization | The response depends on these request headers; a cache must key on them |
Weak ETag W/"…" | "Semantically equal"; strong ETags mean byte-for-byte equal |
The same validator protects writes. Two people edit the same model card; the second save would silently overwrite the first (the "lost update"). With If-Match the server accepts the write only if the resource is still the version you read; otherwise 412 Precondition Failed:
ETAG=$(curl -s -i $BASE/models/embed-small | tr -d '\r' | grep -i '^etag:' | cut -d' ' -f2)
./call -X PATCH $BASE/models/embed-small -H 'Content-Type: application/json' -d '{"status": "testing"}'
./call -X PUT $BASE/models/embed-small -H "If-Match: $ETAG" -H 'Content-Type: application/json' -d '{"dim": 384, "status": "active"}'{"name":"embed-small","dim":768,"status":"testing"} -> HTTP 200
{"detail":"the model changed since you read it"} -> HTTP 412Colleague B's PATCH changed the model after we read it, so our PUT with the old ETag was refused with 412. We must read again, look at what changed, and decide. Use this for configuration, prompts and datasets that several people or jobs update.
Authentication and authorisation
Two different questions, answered in this order:
| Authentication (authn) | Authorisation (authz) | |
|---|---|---|
| Question | Who are you? | Are you allowed to do this? |
| Failure | 401 Unauthorized (badly named: it means unauthenticated) | 403 Forbidden |
| Response must include | WWW-Authenticate: how to authenticate | Nothing special |
| Fix by | Sending valid credentials | Getting a role, scope or permission |
| In our code | bearer() | need("models:write") |
Try all four outcomes: no token, a good token, a good token that lacks permission, and an invalid token.
curl -s -i $BASE/secure/models | tr -d '\r' | grep -i -E '^(HTTP|www-authenticate)'
./call -H 'Authorization: Bearer tok-read' $BASE/secure/models
./call -X POST -H 'Authorization: Bearer tok-read' $BASE/secure/models/embed-small/retire
./call -H 'Authorization: Bearer wrong' $BASE/secure/modelsHTTP/1.1 401 Unauthorized
www-authenticate: Bearer
{"user":"nadia","models":["embed-small"]} -> HTTP 200
{"detail":"requires scope models:write"} -> HTTP 403
{"detail":"invalid token"} -> HTTP 401Authentication succeeded for tok-read (it is Nadia), but retiring a model needs models:write, so: 403. Authorisation can be finer than scopes: whether Nadia may touch this particular model is a per-object check, and forgetting it is the number-one API vulnerability (BOLA; a later page). Return 404 instead of 403 when even revealing that an object exists would leak information.
API keys against bearer tokens
Both travel in a header, and both are "whoever holds it, is it". The differences are in how they are issued, scoped and ended:
| API key | Bearer (access) token | |
|---|---|---|
| Identifies | An application or project | A user or an app, acting with specific scopes |
| Lifetime | Long-lived until revoked | Short (minutes); refreshed with a refresh token |
| Issued by | A dashboard, once | A login or OAuth flow, on demand |
| Typical header | X-API-Key: … (LLM providers use Authorization: Bearer sk-… with long-lived keys) | Authorization: Bearer … |
| Best for | Server-to-server calls, simple public APIs, rate limiting per project | Acting on behalf of users; third-party access with limited scopes |
| If leaked | Valid until someone revokes it: rotate at once | Expires soon; revoke the refresh token |
./call -X POST $BASE/secure/ingest
./call -X POST -H 'X-API-Key: key-ingest-1' $BASE/secure/ingest{"detail":"invalid or missing API key"} -> HTTP 401
{"accepted":true,"service":"ingest-service"} -> HTTP 200Both must travel over HTTPS only, never in a URL (URLs end up in logs and browser history), and never in front-end code that users can read. Store only a hash of API keys in your database, as you would a password (a later page).
OAuth 2.0 and OpenID Connect
When a user clicks "Sign in with Google" or a notebook asks for permission to read your files, no password goes to the app. That is OAuth 2.0: a protocol that lets an app get a limited access token from an authorization server, with the user's consent, so that it can call an API (the resource server). OpenID Connect (OIDC) is a thin layer on top that adds login: if the app also asks for the openid scope it receives an ID token (a signed JWT that says who the user is), and a /userinfo endpoint. OAuth answers "what may this app do?", OIDC answers "who is this person?". The four roles are the user (resource owner), the client (the app), the authorization server and the resource server.
Which flow?
| Situation | Flow (grant) |
|---|---|
| A user signs in to a web, mobile or desktop app (also single-page apps) | Authorization code + PKCE |
| A backend job or service acts as itself (no user): training pipeline, cron, microservice | Client credentials |
| A TV or CLI with no browser | Device authorization grant |
| Keeping a session alive | Refresh token (rotate it on every use) |
| Your own first-party login form posting a username and password | Not OAuth: ordinary login (a later page). The OAuth password grant must not be used (RFC 9700); neither must the old implicit grant |
OAuth 2.1, which folds these lessons into one document, was still a draft in 2026; RFC 9700 ("Best Current Practice for OAuth 2.0 Security", January 2025) is the current rulebook: use PKCE for every authorization code flow, match redirect URIs exactly, give access tokens a short life and rotate refresh tokens.
Client credentials: a service acts as itself
The client proves who it is with an ID and a secret (kept on the server, never in a browser) and receives an access token with the scopes it asked for, if it is allowed to have them:
Service Authorization server API
| POST /token | |
| grant_type=client_credentials | |
| client_id + client_secret + scope | |
|----------------------------------->| |
| access_token (expires in 10 min) |
|<-----------------------------------| |
| GET /secure/models Authorization: Bearer <token> |
|------------------------------------------------------------->|./call -X POST $BASE/oauth/token -d grant_type=client_credentials -d client_id=batch-job -d client_secret=batch-secret -d scope=models:read
./call -X POST $BASE/oauth/token -d grant_type=client_credentials -d client_id=batch-job -d client_secret=wrong
./call -X POST $BASE/oauth/token -d grant_type=client_credentials -d client_id=batch-job -d client_secret=batch-secret -d scope=admin
./call -X POST $BASE/oauth/token -d grant_type=client_credentials -d client_id=batch-job -d client_secret=batch-secret{"access_token":"tok-2","token_type":"Bearer","expires_in":600,"scope":"models:read"} -> HTTP 200
{"error":"invalid_client"} -> HTTP 401
{"error":"invalid_scope"} -> HTTP 400
{"access_token":"tok-3","token_type":"Bearer","expires_in":600,"scope":"models:read models:write"} -> HTTP 200The first token (tok-2) carries only the scope that was asked for: least privilege. A wrong secret is invalid_client, and an unknown scope is invalid_scope. The fourth call asked for nothing special and received the client's default scopes. Use the last token to retire a model:
./call -X POST -H 'Authorization: Bearer tok-3' $BASE/secure/models/embed-small/retire
./call -H 'Authorization: Bearer tok-2' $BASE/secure/models{"name":"embed-small","dim":768,"status":"retired","by":"batch-job"} -> HTTP 200
{"user":"batch-job","models":["embed-small"]} -> HTTP 200Authorization code with PKCE: a user signs in
The app never sees the user's password. It sends the browser to the authorization server; the user logs in and consents there; the server redirects back to the app with a one-time code; the app swaps the code for tokens by calling the server directly. That short-lived code is the weak point: someone who intercepts it (a malicious app registered for the same redirect link on a phone, a browser extension, a log) could swap it first. PKCE (Proof Key for Code Exchange, "pixie") closes that hole. The app invents a random code_verifier, sends only its hash, the code_challenge, at the start, and shows the verifier itself at the end. Only the app that started the flow can.
App (browser/mobile) Authorization server API
| 1. make code_verifier (secret random string)
| code_challenge = BASE64URL(SHA256(code_verifier))
| 2. redirect user: /authorize?response_type=code&client_id&redirect_uri
| &scope&state&code_challenge&code_challenge_method=S256 ------>|
| 3. user logs in, approves scopes |
| 4. redirect to redirect_uri?code=...&state=... <-------------------|
| 5. POST /token: grant_type=authorization_code, code, code_verifier ->|
| 6. server hashes the verifier, compares |
| 7. access_token (+ refresh_token, + id_token if scope has openid) <-|
| 8. GET /api Authorization: Bearer <access_token> ----------------------------->|state is a random value the app also sends and checks when the user comes back, to block forged redirects (CSRF). The challenge is the unpadded Base64URL of the SHA-256 of the verifier; RFC 7636 gives a test vector that you can compute yourself:
import base64
import hashlib
def code_challenge(verifier: str) -> str:
digest = hashlib.sha256(verifier.encode("ascii")).digest()
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
RFC_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
print(code_challenge(RFC_VERIFIER))E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cMIn a real app you would create the verifier with secrets.token_urlsafe(64) (43 to 128 characters). Now run the whole dance against our toy server, with the RFC verifier so that the output is repeatable:
export VERIFIER=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
export CHALLENGE=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
export AUTH="$BASE/oauth/authorize?response_type=code&client_id=web-app&redirect_uri=http://localhost:3000/callback&scope=models:read&state=xyz&code_challenge=$CHALLENGE&code_challenge_method=S256"
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' "$AUTH"
./call -X POST $BASE/oauth/token -d grant_type=authorization_code -d client_id=web-app -d code=code-1 -d code_verifier=$VERIFIER302 http://localhost:3000/callback?code=code-1&state=xyz
{"access_token":"tok-4","token_type":"Bearer","expires_in":600,"scope":"models:read"} -> HTTP 200The first request returned 302 to the app's registered callback with code-1 and our state. The app then exchanged the code, with the verifier, for a token holding just the scope the user approved. Now the attacker's view: they stole a code but do not have the verifier, and a code works only once.
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' "$AUTH"
./call -X POST $BASE/oauth/token -d grant_type=authorization_code -d client_id=web-app -d code=code-2 -d code_verifier=not-the-verifier
./call -X POST $BASE/oauth/token -d grant_type=authorization_code -d client_id=web-app -d code=code-2 -d code_verifier=$VERIFIER
./call -H 'Authorization: Bearer tok-4' $BASE/secure/models302 http://localhost:3000/callback?code=code-2&state=xyz
{"error":"invalid_grant"} -> HTTP 400
{"error":"invalid_grant"} -> HTTP 400
{"user":"nadia","models":["embed-small"]} -> HTTP 200With the wrong verifier the exchange fails (invalid_grant), and because the code is consumed on first use, even the real app cannot reuse it: it must start again. Using the first token, tok-4 (from code-1), works against the API. A real server also: checks the redirect URI character for character against the registered one (ours refuses unknown ones with a 400 rather than redirecting there), expires codes in under a minute, issues a refresh token, and signs access tokens as JWTs the API can verify (the auth page covers JWTs).
The password grant is gone
The old "resource owner password" grant let an app collect your username and password and post them to the token endpoint. It teaches users to type their password into every app, defeats multi-factor login, and cannot work with "Sign in with Google". RFC 9700 says it must not be used. A server that follows the rules refuses it:
./call -X POST $BASE/oauth/token -d grant_type=password -d client_id=web-app -d username=nadia -d password=s3cret-pass{"error":"unsupported_grant_type"} -> HTTP 400Your own first-party app can still show its own login form and call your own login endpoint (the FastAPI tutorials do); that is not an OAuth grant, and it is the only context where passwords reach your code. For "log in with Google, GitHub or Microsoft" use authorization code + PKCE with OIDC, via a library, and never write the token checks yourself.
Scopes
A scope is a named permission the client asks for and the user (or admin) grants: models:read, models:write, openid, email. The token carries the granted scopes, and each endpoint demands the one it needs (as need() does). Design scopes around what a client does, not around your database tables; keep them few; ask for the minimum; and show the user a plain-language consent screen. A scope limits the app; it never replaces checking whether the user may touch an object.
Real-world use
- LLM calls: POST is not idempotent, so providers support idempotency keys; your client retries only 429 and 5xx, and honours
Retry-After. - Model and prompt registries: ETag and
If-Matchstop two engineers overwriting each other's prompt version;If-None-Matchlets a serving process poll for a new model file cheaply. - Dashboards and datasets:
Cache-Control: public, max-ageon slow aggregate endpoints;no-storeon anything personal. - Integrations: an MCP server or a plugin that reads a user's calendar uses authorization code + PKCE; a nightly evaluation job uses client credentials with the narrowest scope.
Common mistakes
- Retrying POST after a timeout. You may charge twice or start two training runs. Retry only idempotent requests, or add an idempotency key.
- Using 403 for "not logged in" (or 401 for "not allowed"). Clients cannot tell whether to log in again. 401 means "authenticate", 403 means "you may not".
- Returning 200 for errors. Monitoring, caches and retry logic read the status line, not your JSON.
- Treating
no-cacheas "do not store". Useno-storefor secrets;no-cacheonly forces revalidation. Also forgettingVarywhen the body depends onAcceptorAuthorization, so a cache hands one user's answer to another. - Skipping PKCE, loose redirect URIs, or the password grant. Use PKCE every time, register exact redirect URIs, and keep client secrets out of browser and mobile apps.
Try it yourself
The lab server from this page is still running. Work in the same terminal.
- Easy: request
/models/embed-smallwith atext/plainAcceptheader and show that revalidating with its ETag gives a 304. (The JSON and text versions have different ETags.) - Easy: send
PUT /models/embed-xltwice with the same body and thenDELETEit twice. Print only the four status codes. - Medium: show a lost-update prevention: read the ETag of
embed-small, change the model with PATCH, then try a PUT withIf-Matchand print the status. - Medium: get a client-credentials token for
batch-jobwith onlymodels:read, call/secure/modelswith it, then try to retire a model and print both status codes. - Hard: write a Python script with
requeststhat performs the complete PKCE flow forweb-app: create a random verifier, compute the challenge, call/oauth/authorizewithout following the redirect, read thecodeandstatefrom theLocationheader, exchange the code, and call/secure/models. Check thatstatematches.
Answers
1. The text representation has its own validator:
TEXT_ETAG=$(curl -s -i -H 'Accept: text/plain' $BASE/models/embed-small | tr -d '\r' | grep -i '^etag:' | cut -d' ' -f2)
curl -s -o /dev/null -w 'text revalidation: HTTP %{http_code}\n' -H 'Accept: text/plain' -H "If-None-Match: $TEXT_ETAG" $BASE/models/embed-small
curl -s -o /dev/null -w 'json with text etag: HTTP %{http_code}\n' -H "If-None-Match: $TEXT_ETAG" $BASE/models/embed-smalltext revalidation: HTTP 304
json with text etag: HTTP 2002. Same state after one or two calls; only the status of the repeat differs:
for method in PUT PUT DELETE DELETE; do
curl -s -o /dev/null -w "$method %{http_code}\n" -X $method $BASE/models/embed-xl -H 'Content-Type: application/json' -d '{"dim": 2048, "status": "active"}'
donePUT 201
PUT 200
DELETE 204
DELETE 4043.
ETAG=$(curl -s -i $BASE/models/embed-small | tr -d '\r' | grep -i '^etag:' | cut -d' ' -f2)
curl -s -o /dev/null -X PATCH $BASE/models/embed-small -H 'Content-Type: application/json' -d '{"dim": 512}'
curl -s -o /dev/null -w 'stale PUT: HTTP %{http_code}\n' -X PUT $BASE/models/embed-small -H "If-Match: $ETAG" -H 'Content-Type: application/json' -d '{"dim": 384, "status": "active"}'stale PUT: HTTP 4124. The token is a JSON field; python -c extracts it:
TOKEN=$(curl -s -X POST $BASE/oauth/token -d grant_type=client_credentials -d client_id=batch-job -d client_secret=batch-secret -d scope=models:read | python -c "import json,sys; print(json.load(sys.stdin)['access_token'])")
curl -s -o /dev/null -w 'list: HTTP %{http_code}\n' -H "Authorization: Bearer $TOKEN" $BASE/secure/models
curl -s -o /dev/null -w 'retire: HTTP %{http_code}\n' -X POST -H "Authorization: Bearer $TOKEN" $BASE/secure/models/embed-small/retirelist: HTTP 200
retire: HTTP 4035. allow_redirects=False keeps the 302 so the script can read the Location header:
import base64
import hashlib
import secrets
from urllib.parse import parse_qs, urlparse
import requests
BASE = "http://localhost:8000"
verifier = secrets.token_urlsafe(64)
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(16)
params = {
"response_type": "code", "client_id": "web-app", "redirect_uri": "http://localhost:3000/callback",
"scope": "models:read", "state": state, "code_challenge": challenge, "code_challenge_method": "S256",
}
redirect = requests.get(f"{BASE}/oauth/authorize", params=params, allow_redirects=False, timeout=5)
query = parse_qs(urlparse(redirect.headers["Location"]).query)
assert query["state"] == [state], "state mismatch: possible forged redirect"
tokens = requests.post(f"{BASE}/oauth/token", timeout=5, data={
"grant_type": "authorization_code", "client_id": "web-app",
"code": query["code"][0], "code_verifier": verifier,
}).json()
api = requests.get(f"{BASE}/secure/models", headers={"Authorization": f"Bearer {tokens['access_token']}"}, timeout=5)
print(redirect.status_code, tokens["scope"], api.status_code, api.json()["user"])302 models:read 200 nadiaStop the server when you are done:
kill $SERVER_PIDSummary
- GET, HEAD and OPTIONS are safe; GET, HEAD, PUT, DELETE and OPTIONS are idempotent; POST is neither, so retry it only with an idempotency key. PUT replaces, PATCH changes part.
- Status codes tell the client what to do next: fix the request (4xx), authenticate (401), give up (403, 404), wait (429), retry (502/503/504).
Acceptnegotiates the format (406 if impossible) andVarytells caches about it.Cache-Controlgives freshness;ETagwithIf-None-Matchgives cheap 304 revalidation;If-Matchwith 412 prevents lost updates.- 401 is "who are you?", 403 is "not allowed"; API keys are long-lived app credentials, bearer tokens are short-lived and scoped.
- OAuth 2.0: authorization code + PKCE for users, client credentials for services, refresh tokens to stay signed in; OIDC adds the ID token for login; never the password grant (RFC 9700).
Next: Designing Robust APIs: Pagination, Rate Limits, Retries and Versioning builds on this: how large result sets, abusive clients, failing networks and changing APIs are handled without breaking anyone.

