Lesson 3 of 9 · 20m
Errors Clients Can Use: HTTP Semantics and Problem Details
How to design useful API errors, map exceptions once instead of everywhere, and avoid the two failure modes: leaking internals and returning meaningless 500s.
Most API error handling fails in one of two ways: either everything becomes a 500 with a traceback in the logs, or every endpoint invents its own JSON shape and client developers are reduced to string matching. Production APIs need an error model as deliberate as their success model.
Status codes are part of the contract
Use status codes for broad meaning and response bodies for detail. 400 means the request itself is wrong, 401 means unauthenticated, 403 means authenticated but not allowed, 404 means not found or deliberately hidden, 409 means conflict with current state, and 422 means the shape was parseable but validation failed.
Do not return 200 with {"success": false}. That breaks caches, retries, monitoring, and every client's intuition.
Centralize domain exception mapping
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
class ConflictError(Exception):
pass
def problem(status: int, title: str, detail: str, type_: str = "about:blank"):
return {"type": type_, "title": title, "status": status, "detail": detail}
@app.exception_handler(ConflictError)
async def conflict_handler(request: Request, exc: ConflictError):
return JSONResponse(
status_code=409,
content=problem(409, "Resource conflict", str(exc)),
media_type="application/problem+json",
)RFC 9457 problem details (application/problem+json) give clients a stable shape. You do not need to implement every optional field; type, title, status, and detail already beat a pile of ad hoc envelopes.
Exceptions are for exceptional control flow
Do not use exceptions to implement normal validation — Pydantic already handles malformed input. Use custom exceptions when deep domain code needs to escape cleanly: duplicate account, payment already captured, deployment no longer running. Map them once at the application boundary.
Never leak internals, but never lose them either
A public error should say what the client can act on, not which line failed. Log the exception with request ID, user or tenant context, and enough metadata to reproduce it. Include the request ID in the problem response so support can correlate the client's report with logs.
{
"type": "https://api.example/problems/rate-limited",
"title": "Rate limit exceeded",
"status": 429,
"detail": "Try again in 30 seconds.",
"request_id": "req_8c67e2"
}Consistency beats cleverness
A client integrating five endpoints should not see five error dialects. Create one error helper, one set of exception handlers, and one logging path. Boring uniformity is what lets generated clients, retry logic, and incident response work.
Field notes
401means 'authenticate';403means 'you are authenticated and still not allowed.' Mixing them breaks clients.- Hide existence when authorization requires it. Sometimes a well-designed 404 is a security feature.
- Do not put stack traces, SQL errors, or internal hostnames in production responses.
- Retries depend on semantics: 409 is often safe to inspect, 500 generally is not blindly retryable.
Was this lesson helpful?