Request Design — Validation, Errors, Pagination & Versioning
Input validation layers, a consistent error model (RFC 9457 problem details), offset vs cursor vs keyset pagination with SQL, filtering/sorting/field selection, partial responses, bulk operations, long-running operations (202 + polling), file uploads, and API versioning strategies.
Validation
# FastAPI + Pydantic: schema validation at the boundary
from pydantic import BaseModel, Field, EmailStr, field_validator
from fastapi import FastAPI
class Item(BaseModel):
product_id: str = Field(pattern=r"^prd_[A-Za-z0-9]{6,}$")
quantity: int = Field(ge=1, le=100)
class CreateOrder(BaseModel):
model_config = {"extra": "forbid"} # reject unknown fields (mass-assignment defence)
items: list[Item] = Field(min_length=1, max_length=50)
email: EmailStr
coupon: str | None = Field(default=None, max_length=32)
@field_validator("coupon")
@classmethod
def upper(cls, v):
return v.upper() if v else v
app = FastAPI()
@app.post("/v1/orders", status_code=201)
def create_order(body: CreateOrder):
... # business-rule validation in the service layer (stock, coupon validity) → 409/422
// Express + Zod
import { z } from "zod";
const CreateOrder = z.object({
items: z.array(z.object({
productId: z.string().regex(/^prd_[A-Za-z0-9]{6,}$/),
quantity: z.number().int().min(1).max(100),
})).min(1).max(50),
email: z.string().email(),
coupon: z.string().max(32).optional(),
}).strict(); // unknown keys → error
app.post("/v1/orders", (req, res) => {
const parsed = CreateOrder.safeParse(req.body);
if (!parsed.success) {
return res.status(422).type("application/problem+json").json(toProblem(parsed.error));
}
// ...
});
| Layer | Validates | Error |
|---|---|---|
| Edge / gateway | body size, content type, auth presence | 413, 415, 401 |
| Schema | types, formats, ranges, required/unknown fields | 400 / 422 |
| Domain | business rules, state transitions | 409 / 422 |
| Database | uniqueness, FKs, CHECKs (race-proof) | map to 409 |
Error model: RFC 9457 Problem Details
HTTP
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/validation",
"title": "Your request parameters didn't validate.",
"status": 422,
"code": "validation_failed",
"request_id": "req_01J9ZK7T0X",
"errors": [
{ "field": "items[0].quantity", "code": "too_large", "message": "must be ≤ 100" },
{ "field": "email", "code": "invalid_format", "message": "is not a valid email" }
]
}
HTTP
HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/invalid-state",
"title": "Order can't be cancelled",
"status": 409,
"code": "order_already_shipped",
"detail": "Order ord_9Kx2 shipped at 2026-10-06T08:00:00Z.",
"instance": "/v1/orders/ord_9Kx2:cancel"
}
Pagination
-- index: (created_at DESC, id DESC)
-- first page
SELECT id, created_at, title FROM post
ORDER BY created_at DESC, id DESC
LIMIT 21; -- fetch one extra to know if there's a next page
-- next page: cursor = base64({"created_at": "...", "id": "..."}) of the last row returned
SELECT id, created_at, title FROM post
WHERE (created_at, id) < ($1, $2) -- row-value comparison
ORDER BY created_at DESC, id DESC
LIMIT 21;
{
"data": [ { "id": "pst_91", "title": "…" } ],
"page": { "next_cursor": "eyJjcmVhdGVkX2F0IjoiMjAyNi0xMC0wN1QxMDoyMVoiLCJpZCI6InBzdF85MSJ9", "has_more": true }
}
| Offset | Cursor / keyset | |
|---|---|---|
| Jump to page N | ✓ | ✗ |
| Deep-page performance | degrades linearly | constant |
| Stable under inserts | ✗ | ✓ |
| Total count | easy (but costly) | separate/estimated |
| Best for | small admin tables | feeds, timelines, public APIs, exports |
Always cap limit (e.g. max 100) and return a default.
Filtering, sorting, field selection
Text
GET /v1/orders?status=paid&created_after=2026-10-01T00:00:00Z&min_total=1000
&sort=-created_at,id&fields=id,status,total&expand=customer&limit=50
- Filtering: explicit, documented params; only allow filters you can index. Complex search → a dedicated
POST /orders/searchwith a JSON body or a search service. - Sorting: allow-list of sortable fields (
-prefix for descending). - Sparse fieldsets (
fields=) and expansion (expand=customer) reduce payloads and round trips.
Bulk operations
HTTP
POST /v1/contacts:batchCreate
{ "contacts": [ {...}, {...} ] }
207 Multi-Status (or 200 with per-item results)
{ "results": [ {"index":0,"status":201,"id":"con_1"}, {"index":1,"status":422,"error":{...}} ] }
Decide (and document) whether a batch is atomic (all-or-nothing in one transaction) or partial (per-item results). Limit batch sizes; for very large imports, upload a file and process asynchronously.
Long-running operations
File uploads
POST /v1/uploads {filename, size, content_type}→ API authorises, returns a pre-signed URL (or multipart part URLs).- Client
PUTs the bytes directly to object storage. - Storage event or
POST /v1/uploads/{id}:complete→ worker validates and processes. - Downloads via CDN with signed URLs for private files.
Versioning
| Strategy | Example | Pros | Cons |
|---|---|---|---|
| Path | /v1/orders | obvious, cache/route friendly | URL changes on major bumps |
| Header | API-Version: 2026-10-01 | clean URLs, fine-grained | less discoverable |
| Media type | Accept: application/vnd.acme.v2+json | HTTP-purist | awkward tooling |
| Query | ?v=2 | easy | caching, clutter |
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.