Building JSON / RESTful APIs (API Design #3)
A team ships an invoicing API. Six months later there are 400 client integrations, and a “small change” — renaming amount to total — breaks 40 of them on a Friday. The postmortem finds the root cause wasn’t the rename. It was that nobody could say, on day one, what the API was: there was no contract document, only the behavior of whatever code was deployed.
This chapter is about building JSON/REST APIs the way you’d build anything load-bearing: design-first, with CRUD mapped honestly onto HTTP, filtering and search that don’t leak your database, pagination that survives a million rows, and a versioning strategy chosen before you need it.
By the end you will be able to take a resource from a whiteboard noun to a versioned, paginated, documented endpoint — and explain each decision to the client who has to live with it.
Design-first: the contract is the artifact
Design-first means the OpenAPI document comes before the implementation. You write the contract, review it like code, generate a mock from it, and only then build the server against it:
openapi: 3.0.3
info: { title: Invoicing API, version: 1.0.0 }
paths:
/invoices:
get:
summary: List invoices
parameters:
- { name: status, in: query, schema: { type: string, enum: [draft, sent, paid] } }
- { name: cursor, in: query, schema: { type: string } }
responses:
'200':
description: A page of invoices
content:
application/json:
schema: { $ref: '#/components/schemas/InvoicePage' }
The payoff is parallelism and honesty: frontend teams code against the mock, the spec review catches amount vs total while changing it costs nothing, and the spec becomes the source for docs (Chapter 8) and contract tests (Chapter 12). Code-first inverts this — the contract is whatever the framework serializes today, and drift is guaranteed.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.6cm, minimum height=0.75cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=orange!20] (s) at (0,0) {OpenAPI spec};
\node[b, fill=blue!10] (m) at (-3.4,-1.4) {mock server};
\node[b, fill=green!10] (d) at (0,-1.4) {docs};
\node[b, fill=gray!12] (t) at (3.4,-1.4) {contract tests};
\node[b, fill=green!10] (i) at (0,-2.7) {implementation};
\draw[a] (s) -- (m); \draw[a] (s) -- (d); \draw[a] (s) -- (t);
\draw[a] (t) -- node[right, font=\rmfamily\scriptsize] {validates} (i);
\end{tikzpicture}
CRUD maps cleanly onto HTTP
For each resource, the four operations land on the method table from Chapter 1 — but the details are where APIs go wrong:
| Operation | Call | Success | Body | Notes |
|---|---|---|---|---|
| Create | POST /invoices |
201 + Location: /invoices/9 |
new resource | server assigns id |
| Read | GET /invoices/9 |
200 |
resource | cacheable |
| Replace | PUT /invoices/9 |
200 |
full resource | idempotent |
| Modify | PATCH /invoices/9 |
200 |
changed fields only | partial |
| Delete | DELETE /invoices/9 |
204 |
empty | idempotent |
Three details earn their keep. POST returns 201 Created with a Location header — the client learns the new id without a second request. PUT is replace: send the whole document, which is what makes it idempotent and safe to retry. PATCH is modify: send only the delta, which saves bandwidth but is not automatically idempotent (JSON Merge Patch vs JSON Patch is a real decision — RFC 7386 vs RFC 6902).
# FastAPI: create returns 201 + Location, replace is idempotent.
from fastapi import FastAPI, Response, status
app = FastAPI()
DB: dict[str, dict] = {}
@app.post("/invoices", status_code=status.HTTP_201_CREATED)
def create(invoice: dict, response: Response):
new_id = f"inv_{len(DB) + 1:06d}"
DB[new_id] = {"id": new_id, **invoice}
response.headers["Location"] = f"/invoices/{new_id}"
return DB[new_id]
@app.put("/invoices/{iid}")
def replace(iid: str, invoice: dict):
DB[iid] = {"id": iid, **invoice} # same input → same state: idempotent
return DB[iid]
Filtering, sorting, and search
List endpoints grow requirements fast: “only unpaid”, “newest first”, “search by customer name”. The contract for all three is the query string:
GET /invoices?status=sent&overdue=true&sort=-issued_at&q=acme
- Filtering — one parameter per dimension:
status=sent,min_total=1000. Repeatable, composable, cacheable (each combination is a distinct URL). - Sorting —
sort=-issued_at,total(minus for descending). Whitelist sortable fields server-side; a raw?sort=passed into SQL is an injection vector. - Search —
q=is a different beast from filters: relevance-ranked, fuzzy, language-aware. Keep it one parameter, and resist the urge to invent a filter DSL in the query string. When filters get genuinely complex (nested AND/OR), accept a JSON filter in aPOST /invoices/searchbody — pragmatism over purity.
The rule that keeps you honest: a URL is an address, not a program. If your query language needs a parser, it wants a request body and probably its own endpoint.
Pagination: cursors beat offsets at scale
Nobody returns a million rows. The two pagination schemes:
Offset — ?offset=200&limit=50 becomes OFFSET 200 LIMIT 50 in SQL. Simple, page-jumpable (“go to page 9”), and quietly broken at scale. The database must scan and discard the offset rows, so cost grows linearly with depth:
\[ T_{\text{offset}}(k) = O(k) \quad \text{rows scanned for page at offset } k \]
Worse, it is inconsistent under writes: a new row inserted at the front while a user pages forward makes them see a row twice and skip another.
Cursor — the response hands back an opaque token pointing at the last item; the next request continues from there:
{
"data": [ {"id": "inv_000201", ...}, ... ],
"next_cursor": "eyJsYXN0X2lkIjoiaW52XzAwMDI1MCJ9",
"has_more": true
}
The query becomes WHERE id > :cursor ORDER BY id LIMIT 50 — \(O(\log n)\) with an index, constant at any depth, and immune to front-insertions (the cursor anchors to a value, not a position). The cost: no random page access, and the cursor must be treated as opaque (clients never parse it; you can re-encode it in v2 without breaking anyone).
import base64, json
def encode_cursor(last_id: str) -> str:
return base64.urlsafe_b64encode(json.dumps({"last": last_id}).encode()).decode()
def page_query(cursor: str | None, limit: int = 50):
after = json.loads(base64.urlsafe_b64decode(cursor))["last"] if cursor else ""
# SELECT * FROM invoices WHERE id > :after ORDER BY id LIMIT :limit+1
rows = fetch_rows_after(after, limit + 1) # one extra row...
has_more = len(rows) > limit # ...tells us if more exist
return rows[:limit], encode_cursor(rows[limit - 1]["id"]) if has_more else None
The limit + 1 trick answers has_more without a COUNT(*) — a count over a big filtered table is often the most expensive query on the page.
Versioning strategies
You will change the contract. The only question is whether clients find out from a migration guide or from a 500. The three mainstream schemes:
| Scheme | Looks like | Pros | Cons |
|---|---|---|---|
| URL path | /v2/invoices |
obvious, cache-friendly, testable in a browser | “versions the whole API”, URL purists object |
| Header | Accept: application/vnd.acme.v2+json |
clean URLs, versions per-representation | invisible, harder to debug/curl |
| Query param | /invoices?version=2 |
easy to try | easy to drop, muddles caching keys |
URL versioning (/v1/, /v2/) dominates public APIs for a reason: a developer can see the version, and support can reproduce a report verbatim. Whatever you pick, three rules make versions survivable: versions are additive within (v1 only ever gains optional fields; breaking changes get v2), few in number (two live versions at once, not five), and sunset with notice — deprecation headers and a published timeline, which Chapter 14 covers as lifecycle management.
Pitfalls
- Code-first drift. The spec is written “later” (never), and the real contract becomes the serializer’s output. Write the OpenAPI doc first and generate from it.
PUTthat merges. A replace endpoint that silently behaves like patch breaks idempotent retries — two concurrent PUTs leave a blend. Replace wholesale or name itPATCH.- Offset pagination on big, busy tables. Deep pages are slow (\(O(k)\) scans) and skip/duplicate rows under writes. Move hot lists to cursors early.
- Letting
sort=reach SQL. Concatenating the parameter intoORDER BYis SQL injection. Whitelist allowed columns. - Versioning per-endpoint ad hoc.
/v2/invoicesnext to/invoices/v3next to header-versioned/paymentsmeans no client knows what it’s calling. One scheme, one policy, documented. - Breaking within a version. “It’s still v1, we just renamed a field” is how you lose integrators. Additive-only within a version; renames are new versions.
Why does POST return 201 with a Location header instead of just 200 with the body? Compare offset and cursor pagination on a 10M-row table with inserts every second — which one lies to users, and which one is slow, and why? You must rename amount to total — walk through the additive-then-sunset path.
ASolution
201 plus Location tells the client both that a new resource was created (not merely read) and where it lives, saving a second request to discover the id. Offset pagination is both slow (every deep page scans \(O(k)\) rows) and inconsistent (front-inserts shift positions, causing duplicates and skips); cursor pagination is \(O(\log n)\) and stable because it anchors to a value. Ship total alongside amount in v1, announce deprecation of amount with a sunset date, and remove it only in v2 (or after the sunset if staying within v1 under your policy) — clients migrate on their own schedule.
Next: Real-time APIs (API Design #4) — polling, SSE, WebSockets, and webhooks, and how to choose the cheapest one that works.