Errors, Pagination and Filtering Clients Can Rely On
Fix a first-cut list endpoint so errors follow RFC 9457 Problem Details, paging works on a shifting feed, and filters, sorting and rate limits are part of the contract.
Contentsand lesson path
On this page
- The brief
- Step 1: errors as Problem Details
- Step 2: why the feed breaks offset paging
- Step 3: a cursor that works
- Step 4: filters, sorting and the rate limit
- Run the demo yourself
- The mistakes this design closes off
- Check your understanding
- Apply it
- Review prompt
Lessons of API Design
- From Domain Nouns to Resources and URLs Concept · 20 min
- Errors, Pagination and Filtering Clients Can Rely On Worked example · 25 min
- Safe Retries, Long-Running Operations, Concurrent Updates and Versioning Concept · 30 min
- Lab: Contract-First Design with OpenAPI Lab · 30 min
- Beyond REST: Sketching a GraphQL Schema and a gRPC Service Worked example · 25 min
- Check: Review a Flawed API Design Knowledge check · 10 questions
What you will learn
- Specify a machine-readable error format (Problem Details) and a pagination, filtering and sorting scheme, choosing cursor or offset pagination with stated trade-offs.
Prerequisites: HTTP & APIs
01. The brief
The team-tasks API from the resource lesson has a first cut of its list endpoint, and a code review found three problems. Errors come back as {"error": "..."} with whatever status the handler happened to pick, so every client parses errors its own way. GET /teams/t7/tasks returns all the tasks, which was fine with eleven tasks and will not be at eleven thousand. And the review wants filter and sort parameters documented, not discovered by reading the server code.
You will fix all three in this worked example, on a running FastAPI app exercised with httpx. By the end, every error is a standard Problem Details document, the list endpoint pages with a cursor that survives new data arriving mid-walk, and the contract states exactly which query parameters exist and what happens when they are wrong. The same decisions appear in the OpenAPI lab later in this skill, so what you settle here is what you will publish there.
02. Step 1: errors as Problem Details
RFC 9457 defines a single JSON shape for errors, served with the media type application/problem+json. Five members do the work: type, a URI that identifies the kind of problem (clients branch on this, not on message text); title, a short human summary; status, the HTTP status code repeated for convenience; detail, a human-readable explanation of this occurrence; and instance, a URI reference that identifies this specific occurrence (many APIs use the request path, as this demo does, or a per-error id that support can look up). All five members are optional, and a missing type means "about:blank". Anything else can be added as an extension member — the standard was designed to grow.
The status code still leads: it is what generic clients, proxies and dashboards read first, as covered when you learned to read status classes. Problem Details makes the story machine-readable after the status has said something is wrong. On the server, one helper function and one exception handler cover the whole API:
def problem(status_code, type_slug, title, detail,
instance, **extra) -> JSONResponse:
body = {
"type": f"https://api.example.com/problems/{type_slug}",
"title": title,
"status": status_code,
"detail": detail,
"instance": instance,
**extra,
}
return JSONResponse(status_code=status_code, content=body,
media_type="application/problem+json")
def to_error(e: dict) -> dict:
where, *path = e["loc"] # where: "body", "query", "path" or "header"
item = {"location": where, "detail": e["msg"]}
if e["type"] == "json_invalid": # unparseable body: path is a char offset
item["position"] = path[0] if path else None
elif where == "body": # RFC 6901 JSON Pointer into the request body
item["pointer"] = "#" + "".join(f"/{p}" for p in path)
else:
item["parameter"] = ".".join(str(p) for p in path)
return item
@app.exception_handler(RequestValidationError)
async def validation_problem(request, exc):
errors = [to_error(e) for e in exc.errors()]
return problem(422, "validation-error",
"The request is invalid",
"One or more values failed validation.",
request.url.path, errors=errors)GET /teams/nope/tasks -> 404 (application/problem+json)
{"type":"https://api.example.com/problems/team-not-found",
"title":"Team not found","status":404,
"detail":"No team with id 'nope'.",
"instance":"/teams/nope/tasks"}
POST /teams/t7/tasks -> 422 (application/problem+json)
{"type":"https://api.example.com/problems/validation-error",
"title":"The request is invalid","status":422,
"detail":"One or more values failed validation.",
"instance":"/teams/t7/tasks",
"errors":[{"location":"body",
"detail":"String should have at least 1 character",
"pointer":"#/title"}]}
POST /teams/t7/tasks (no body) -> 422 (application/problem+json)
... "errors":[{"location":"body","detail":"Field required",
"pointer":"#"}]}
GET /teams/t7/tasks?limit=-1 -> 422 (application/problem+json)
... "errors":[{"location":"query",
"detail":"Input should be greater than or equal to 1",
"parameter":"limit"}]}
POST /teams/t7/tasks -> 409 (application/problem+json)
{"type":"https://api.example.com/problems/duplicate-title",
"title":"Title already used","status":409,
"detail":"A task titled 'Task 1' already exists.",
"instance":"/teams/t7/tasks","conflicting_title":"Task 1"}loc[0] in each FastAPI validation error says where the bad value was: body, query, path or header. Body errors get a JSON Pointer (#/assignee/name for a nested field, # for a missing body), and parameter errors name the parameter. A body that is not valid JSON at all is the exception: its loc holds a character offset, not a field, so it is reported as position (a trailing comma in {"title": "x",} gives "position": 14). Indexing loc[1] directly is a classic bug: a request with no body has a one-element loc, and the handler itself crashes with a 500.
Three different failures, one parser. A client switches on type — team-not-found means give up on this team, validation-error means show the errors pointers next to the form fields, duplicate-title means offer a rename — and the extension members carry exactly the data each case needs. Publish the list of problem type URIs in your documentation and keep it stable: those URIs are part of your contract, like paths and status codes.
03. Step 2: why the feed breaks offset paging
Offset paging (?offset=2&limit=2, "page 2") is the familiar design, and for a small, slowly changing admin table it is the right one: it supports jumping to page 7, showing "page 2 of 13", and any sort order the client asks for. Its cost appears on a feed that grows while the client walks it. The database must read and throw away every skipped row — deep pages get slower in proportion to their depth — and any insert shifts every row after it, so items repeat or vanish between pages:
page 2 before insert: ['k104', 'k103']
page 2 after insert: ['k105', 'k104']The same insert, seen by a cursor walk, is invisible: a cursor does not say "row 3 of a moving list", it says "resume after this exact item". That single change is what makes cursors the default for feeds, timelines and anything with a write rate.
04. Step 3: a cursor that works
A cursor has one hard requirement: it must mark a unique position in a total order. Sorting by created_at alone is not a total order when two tasks share a timestamp — a naive created_at > :last cursor silently drops the rows tied with the last item on a page. The fix is a tie-breaker: sort by (created_at, id), and encode both values into the cursor. Serve the cursor as an opaque string (base64 of the encoded position), so clients treat it as a token and the server stays free to change its internal format later. The response returns next_cursor, set to null on the last page — no extra "are we done" flag to misread.
def encode_cursor(task: dict) -> str:
raw = f"{task['created_at'].isoformat()}|{task['id']}"
return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
def decode_cursor(cursor: str) -> tuple[datetime, str]:
try:
padded = cursor + "=" * (-len(cursor) % 4)
raw = base64.urlsafe_b64decode(padded).decode()
created_at, task_id = raw.split("|")
when = datetime.fromisoformat(created_at)
if when.tzinfo is None: # naive times cannot be compared
raise ValueError("cursor time has no UTC offset")
return when, task_id
except ValueError: # bad base64, bad UTF-8 or wrong shape
raise ProblemError(422, "invalid-cursor", "Invalid cursor",
"The cursor is not one this API issued.")
@app.get("/teams/{team_id}/tasks")
def list_tasks(team_id: str,
limit: int = Query(20, ge=1, le=100),
cursor: str | None = None,
state: Literal["open", "done"] | None = None,
assignee: str | None = None):
if team_id not in TEAMS:
raise ProblemError(404, "team-not-found", "Team not found",
f"No team with id '{team_id}'.")
rows = sorted(TASKS.values(),
key=lambda t: (t["created_at"], t["id"]),
reverse=True)
if state is not None:
rows = [t for t in rows if t["state"] == state]
if assignee is not None:
rows = [t for t in rows if t["assignee"] == assignee]
if cursor is not None:
marker = decode_cursor(cursor)
rows = [t for t in rows
if (t["created_at"], t["id"]) < marker]
page = rows[:limit]
return {"items": page,
"next_cursor": encode_cursor(page[-1])
if len(rows) > limit else None}page ['k106', 'k105'] next_cursor=yes
page ['k104', 'k103'] next_cursor=yes
page ['k102', 'k101'] next_cursor=no
walked: ['k106', 'k105', 'k104', 'k103', 'k102', 'k101']
after inserting a newer task, the same cursor still
resumes at: ['k104', 'k103']Every task that existed when the walk began appears exactly once, even though the feed changed underneath, and re-using a saved cursor resumes in the right place; the newer task shows up the next time a client starts from the first page. The trade-offs are real and worth stating in the contract: no jumping to page numbers, no cheap exact total count (one extra count query if you must show one), and sorting fixed to the cursor order. Google's AIP-131 describes exactly this page_token shape if you want a large-scale reference.
05. Step 4: filters, sorting and the rate limit
Filtering follows one rule: every parameter is enumerated, typed and validated. state and assignee above filter by equality; a wrong state value is a client mistake, so the answer is a 422 Problem Details document naming the parameter (typing state as Literal["open", "done"] and limit with ge=1, le=100 makes FastAPI do this for you; without the lower bound, limit=-1 would turn rows[:limit] into "every row but the last"), never a silent empty list — an empty list is a valid answer saying "no such tasks", and conflating it with "no such state value" hides bugs for weeks. Sorting, when you add it, takes a whitelist (sort=created_at:asc or sort=created_at:desc, nothing else), because a sort key you did not index is a slow query, and a sort key you did not plan for can leak data through ordering. Full-text search is a parameter (?q=) on the same collection or a dedicated search operation, not a separate resource per screen.
One more response belongs in the same contract: 429 Too Many Requests. When the server throttles a client, it answers 429 with Retry-After (seconds until the next attempt is allowed) and, increasingly, the RateLimit and RateLimit-Policy fields from draft-ietf-httpapi-ratelimit-headers, so clients can back off before hitting the wall. That is still an Internet-Draft, and its syntax has changed several times. The output below follows draft 12 (20 November 2026): after the quoted policy name, RateLimit-Policy gives q (quota) and w (window in seconds), and RateLimit gives a (available quota) and w (seconds that quota applies for). Draft 11 used r and t instead, and many gateways still send that form. The demo has no limiter, so this shows what one following draft 12 sends:
request 1 -> 200 RateLimit-Policy: "default";q=3;w=60
RateLimit: "default";a=2;w=60
request 2 -> 200 RateLimit-Policy: "default";q=3;w=60
RateLimit: "default";a=1;w=60
request 3 -> 200 RateLimit-Policy: "default";q=3;w=60
RateLimit: "default";a=0;w=60
request 4 -> 429 RateLimit-Policy: "default";q=3;w=60
RateLimit: "default";a=0;w=60
Retry-After: 60A client that reads these headers paces itself instead of getting locked out, and your documentation of 429 is what makes it do so. The same signalling reappears in the next lesson, where retries of unsafe requests need more than patience.
06. Run the demo yourself
Save parts 1 to 4, in order, as demo02_errors_pagination.py; the two excerpts above are parts 2 and 3. Part 1 holds the imports, the seed data (all times in UTC), ProblemError and the create route. Part 4 sends the requests behind the outputs above through httpx, in process.
import asyncio
import base64
from datetime import UTC, datetime, timedelta
from typing import Literal
import httpx
from fastapi import FastAPI, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
app = FastAPI()
TEAMS = {"t7"}
TASKS: dict[str, dict] = {}
T0 = datetime(2026, 10, 24, 9, 0, tzinfo=UTC) # created_at is always UTC
def add_task(title: str, minute: int) -> str:
task_id = f"k{101 + len(TASKS)}"
TASKS[task_id] = {"id": task_id, "title": title, "assignee": "ana",
"state": "open", "created_at": T0 + timedelta(minutes=minute)}
return task_id
def seed() -> None: # six tasks, k101 (oldest) to k106 (newest)
TASKS.clear()
for i in range(6):
add_task(f"Task {i + 1}", i)
class ProblemError(Exception):
def __init__(self, status: int, type_slug: str, title: str, detail: str,
**extra) -> None:
super().__init__(detail)
self.status, self.type_slug, self.title = status, type_slug, title
self.detail, self.extra = detail, extra
@app.exception_handler(ProblemError)
async def problem_error(request: Request, exc: ProblemError) -> JSONResponse:
return problem(exc.status, exc.type_slug, exc.title, exc.detail,
request.url.path, **exc.extra)
class TaskIn(BaseModel):
title: str = Field(min_length=1)
assignee: str | None = None
@app.post("/teams/{team_id}/tasks", status_code=201)
def create_task(team_id: str, task_in: TaskIn) -> dict:
if team_id not in TEAMS:
raise ProblemError(404, "team-not-found", "Team not found",
f"No team with id '{team_id}'.")
if any(t["title"] == task_in.title for t in TASKS.values()):
raise ProblemError(409, "duplicate-title", "Title already used",
f"A task titled '{task_in.title}' already exists.",
conflicting_title=task_in.title)
task_id = add_task(task_in.title, len(TASKS))
return {"id": task_id, "title": task_in.title}def newest_first() -> list[str]:
rows = sorted(TASKS.values(), key=lambda t: (t["created_at"], t["id"]),
reverse=True)
return [t["id"] for t in rows]
async def main() -> None:
seed()
transport = httpx.ASGITransport(app=app) # calls the app in process
async with httpx.AsyncClient(transport=transport,
base_url="http://api.test") as c:
for method, url, body, note in [
("GET", "/teams/nope/tasks", None, ""),
("POST", "/teams/t7/tasks", {"title": ""}, ""),
("POST", "/teams/t7/tasks", None, " (no body)"),
("GET", "/teams/t7/tasks?limit=-1", None, ""),
("POST", "/teams/t7/tasks", {"title": "Task 1"}, ""),
]:
r = await c.request(method, url, json=body)
print(f"{method} {url}{note} -> {r.status_code}"
f" ({r.headers['content-type']})")
print(r.text)
print()
# offset paging: what ?offset=2&limit=2 returns, before and after an insert
print("page 2 before insert:", newest_first()[2:4])
add_task("Newer task", 10)
print("page 2 after insert: ", newest_first()[2:4])
seed() # start again from the same six tasks, then walk with a cursor
url, seen, saved = "/teams/t7/tasks?limit=2", [], None
while url:
data = (await c.get(url)).json()
ids = [t["id"] for t in data["items"]]
seen += ids
print(f"page {ids} next_cursor={'yes' if data['next_cursor'] else 'no'}")
saved = saved or data["next_cursor"] # keep the cursor from page 1
url = (f"/teams/t7/tasks?limit=2&cursor={data['next_cursor']}"
if data["next_cursor"] else None)
print("walked:", seen)
add_task("Newer task", 10)
data = (await c.get(f"/teams/t7/tasks?limit=2&cursor={saved}")).json()
print("after inserting a newer task, the same cursor still")
print("resumes at:", [t["id"] for t in data["items"]])
asyncio.run(main())uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install fastapi==0.163.1 pydantic==2.14.3 httpx==0.28.1
python demo02_errors_pagination.py07. The mistakes this design closes off
Each failure mode the review found ships in real APIs:
08. Check your understanding
09. Apply it
Start from the full demo02_errors_pagination.py and extend it: add a sort parameter with a whitelist of the two allowed orders and a 422 problem (type validation-error) for anything else; add assignee to the cursor contract; then write the problem type URIs your version of the API can return into a list you would publish. For your team-tasks API, decide per collection which paging scheme fits and write the one-sentence trade-off next to each decision; the OpenAPI lab will need them.
10. Review prompt
Without looking back: name the five Problem Details members and what a client switches on to branch between error kinds. State the two things that break offset paging on a growing feed, and the two features cursors give up in exchange. Explain why a cursor needs a tie-breaker column, why limit must have a maximum, and which headers a 429 response should carry.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.