Lesson 27 of 59API design in depth
Error Responses Clients Can Rely On
Replace FastAPI's mixed error shapes with RFC 9457 Problem Details: one model, one handler set, precise status codes, no leaked internals.
The mobile team files a ticket: "Please document your errors." They have written three parsers for your API. A 404 comes back as {"detail": "Order not found"}. A validation failure comes back as {"detail": [ ... ]}, a list instead of a string under the same key. A crash comes back as the plain text Internal Server Error, which is not JSON at all, so their JSON parser throws inside the error handler and the app shows a blank screen. In Errors and Middleware you learned to raise domain exceptions and translate them in one handler. This lesson picks the format those handlers produce, RFC 9457 Problem Details, and wires it through every path an error can take in FastAPI.
Three shapes from one API
Here is what a stock FastAPI app sends for three different failures:
HTTP/1.1 404 Not Found
content-type: application/json
{"detail": "Order not found"}HTTP/1.1 422 Unprocessable Content
content-type: application/json
{"detail": [{"type": "int_parsing", "loc": ["body", "items", 0, "qty"],
"msg": "Input should be a valid integer", "input": "two"}]}HTTP/1.1 500 Internal Server Error
content-type: text/plain; charset=utf-8
Internal Server ErrorEach one is reasonable alone. Together they force every client to inspect the status, then guess the body type, then guess the shape of detail. Worse, nothing in any of them is stable enough to branch on. A client that wants to show "only 2 left in stock" has to match on the English text of a message you might reword next week. The validation shape also echoes input back, which is a problem when the field was a password or a card number.
RFC 9457 in one screen
RFC 9457 (July 2023) defines a standard JSON error body and replaces RFC 7807, which said the same thing with a few gaps. The media type is application/problem+json. A problem document has five standard members, all optional:
| Member | Meaning | Who reads it |
|---|---|---|
type | A URI identifying the kind of problem. Defaults to about:blank | Client code: this is what you switch on |
title | A short summary of the kind, the same for every occurrence | Humans, logs |
status | The HTTP status code, copied into the body | Clients that lose the header (queues, logs) |
detail | An explanation of this occurrence | Humans; never parse it |
instance | A URI reference for this occurrence | Support tickets, log lookups |
Anything else is an extension member: errors for field problems, trace_id for support, available for the stock count. Clients must ignore extensions they do not understand, so you can add context without a new format.
The rule that makes it work: the type is a stable identifier, versioned like a field name. https://api.example.com/problems/insufficient-stock means the same thing for as long as the API lives, and ideally it resolves to a page explaining the problem and what to do. The RFC tells clients to use type as the primary identifier. title and detail are prose and can change. When there is nothing more specific to say than the status code, use about:blank, and then title should be the standard status phrase, such as Not Found.
{
"type": "https://api.example.com/problems/insufficient-stock",
"title": "Not enough stock",
"status": 409,
"detail": "Only 2 units of MUG-01 are available.",
"instance": "/v2/orders",
"sku": "MUG-01",
"available": 2
}For validation, the RFC's own example uses an errors extension: a list of objects each with a detail and a pointer, a JSON Pointer (RFC 6901) written as a URI fragment, such as #/items/0/qty. Follow that convention and every client knows which form field to highlight.
The model and the exception hierarchy
Start with a Pydantic model for the document and a helper that builds responses with the right media type:
from typing import Any
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict
PROBLEM_JSON = "application/problem+json"
PROBLEM_BASE = "https://api.example.com/problems/"
class FieldError(BaseModel):
detail: str
pointer: str | None = None # body fields, "#/items/0/qty"
parameter: str | None = None # query, path or header parameters, "limit"
class ProblemDetail(BaseModel):
model_config = ConfigDict(extra="allow") # extension members
type: str = "about:blank"
title: str
status: int
detail: str | None = None
instance: str | None = None
def problem(status: int, title: str, type_: str = "about:blank", headers: dict | None = None, **extra: Any) -> JSONResponse:
body = ProblemDetail(type=type_, title=title, status=status, **extra)
return JSONResponse(
body.model_dump(mode="json", exclude_none=True),
status_code=status,
media_type=PROBLEM_JSON,
headers=headers,
)Then make the domain exceptions from Errors and Middleware carry what a problem needs. Each subclass fixes its own status, type and title, so a service only supplies the occurrence-specific detail:
class AppError(Exception):
status = 400
slug = "bad-request"
title = "Bad request"
def __init__(self, detail: str, **extra):
super().__init__(detail)
self.detail = detail
self.extra = extra # becomes extension members
class NotFound(AppError):
status, slug, title = 404, "not-found", "Resource not found"
class PermissionDenied(AppError):
status, slug, title = 403, "permission-denied", "Not allowed"
class Conflict(AppError):
status, slug, title = 409, "conflict", "Conflicts with current state"
class InsufficientStock(Conflict):
slug, title = "insufficient-stock", "Not enough stock"from fastapi import FastAPI, Request
from app.api.problems import PROBLEM_BASE, problem
from app.errors import AppError
def install_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def app_error(request: Request, exc: AppError):
return problem(
exc.status, exc.title, PROBLEM_BASE + exc.slug,
detail=exc.detail, instance=request.url.path, **exc.extra,
)A service now raises InsufficientStock("Only 2 units of MUG-01 are available.", sku="MUG-01", available=2) and the client gets the document above. The service never imports anything from FastAPI. install_handlers is a function so you can call it on every app, including mounted sub-apps, which do not inherit their parent's handlers (Evolving an API Without Breaking Clients shows why that matters).
Reshaping validation errors
FastAPI raises RequestValidationError before your route runs. Override its handler to turn Pydantic's error list into problem errors. Each Pydantic error has a loc tuple whose first item says where the value came from (body, query, path, header, cookie), followed by the path inside it.
Press Run (⌘ Enter) to see what happens.Using to_pointer from above, what does this print?
print(to_pointer(("tags", "x~y")))The handler itself is short:
from fastapi.exceptions import RequestValidationError
@app.exception_handler(RequestValidationError)
async def validation_error(request: Request, exc: RequestValidationError):
return problem(
422, "Validation failed", PROBLEM_BASE + "validation",
detail="One or more fields are invalid.",
errors=to_problem_errors(exc.errors()),
)Two details you only find by testing. First, dropping input is a security fix, not tidiness: the default handler sends back whatever the client sent, including passwords, into logs and error trackers. Second, input is not always JSON-safe. A body that FastAPI could not parse arrives as raw bytes, and a handler that puts it straight into JSONResponse crashes with a TypeError inside your error handler. The default handler runs jsonable_encoder for this reason. Not echoing input avoids the problem entirely.
Router errors and the catch-all
Your AppError handler does not see every error. When no route matches, Starlette's router raises Starlette's HTTPException (404 or 405) before FastAPI is involved. FastAPI's own HTTPException is a subclass of it, so register the handler on the Starlette class and you cover both:
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(StarletteHTTPException)
async def http_error(request: Request, exc: StarletteHTTPException):
return problem(exc.status_code, str(exc.detail), headers=exc.headers)Pass exc.headers through. A 405 from the router carries an Allow header, a 401 needs WWW-Authenticate, and a handler that drops them breaks clients that follow the spec.
Last, the catch-all for bugs. An @app.exception_handler(Exception) handler is special in Starlette: it is installed in ServerErrorMiddleware, the outermost layer of the onion you saw in Errors and Middleware. It runs outside your own middleware, so headers your request-id middleware adds on the way out are not on this response. Read the id from a ContextVar set early in the request, or generate one here:
import logging
log = logging.getLogger("api")
@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception):
trace_id = current_request_id() or uuid.uuid4().hex
log.exception("unhandled error", extra={"trace_id": trace_id, "path": request.url.path})
return problem(500, "Internal Server Error", trace_id=trace_id)The response says nothing about what broke: no exception class, no SQL, no file paths, no stack. The log line has all of it, keyed by the trace_id the user can read out to support. Uvicorn still logs the traceback too, and in tests TestClient re-raises the exception unless you pass raise_server_exceptions=False, which you want in the test that checks this handler.
A body fails validation, or a service raises InsufficientStock. ExceptionMiddleware finds the handler by class and returns a problem. Your middleware still adds its headers on the way out.
Choosing the status code precisely
The type carries the detail, but the status code is still what proxies, retries, dashboards and alerting read. The cases teams argue about:
- 400 vs 422. FastAPI uses
422for any request that fails validation, including invalid JSON. Keep that, and use400for requests that parse but make no sense together in ways a schema cannot express, or follow your style guide if it picks one for everything. Consistency matters more than the choice. - 401 vs 403.
401means "who are you?": missing or invalid credentials, and it must includeWWW-Authenticate.403means "I know who you are, and no". - 404 to hide existence. If a user may not even know order
ord_42exists, return404, not403. A403confirms the id is real, which helps anyone enumerating ids. - 409 vs 412.
409is a conflict with current state (duplicate email, not enough stock).412is a failedIf-Matchprecondition. - 415. The right code for a body in a media type you do not accept. FastAPI does not send it for you: since 0.132 it refuses to parse a body as JSON unless the
Content-Typeis JSON, and the result is a422saying the body is not a valid object. Oldcurlexamples without-H "Content-Type: application/json"now fail this way. If you want415, check the header in a dependency. - 429 with a
Retry-Afterheader, so well-behaved clients know how long to wait. - 500 vs 502, 503, 504.
500is your bug.502means an upstream you called returned garbage,503means you are deliberately refusing (overload, maintenance, addRetry-After), and504means an upstream timed out. The distinction tells the on-call engineer where to look, and tells clients which errors are worth retrying.
Match each situation to the status code the API should return.
Documenting problems in OpenAPI
Overriding a handler does not change the docs. FastAPI still advertises its default HTTPValidationError schema for 422 and nothing for your 404s and 409s, so generated clients have no type for the error body. Declare them on the route, or once on the router:
PROBLEM_SCHEMA = {"schema": {"$ref": "#/components/schemas/ProblemDetail"}}
PROBLEM_RESPONSES = {
code: {"model": ProblemDetail, "content": {PROBLEM_JSON: PROBLEM_SCHEMA}}
for code in (404, 409, 422)
}
router = APIRouter(prefix="/v2", responses=PROBLEM_RESPONSES)model registers the schema under components and replaces the default 422 entry. FastAPI files it under the route's normal media type, application/json, so the content entry adds application/problem+json pointing at the same schema. Generated TypeScript and Python clients then know that a 409 body has type, title and status.
Consuming problems on the client
A good client switches on type, falls back to status, and survives responses that are not problems at all: a load balancer's HTML 502 page will never be application/problem+json.
Press Run (⌘ Enter) to see what happens.A route raises InsufficientStock. Order what happens until the client shows a message.
- Tap the steps below in the right order.
AppError and RequestValidationError only. A client calls PATCH /v2/orders on a path that only supports GET and POST. What does it receive?- Problem Details
- RFC 9457's standard JSON error body, served as
application/problem+json. It replaced RFC 7807. - problem type
- The
typeURI that identifies a kind of problem. It is stable, documented, and what client code branches on. - about:blank
- The default
type, meaning the problem has no meaning beyond its HTTP status code. - extension member
- Any extra field in a problem document, such as
errors,trace_idoravailable. - JSON Pointer
- RFC 6901 syntax for a location in a JSON document, such as
#/items/0/qty, with~0and~1escapes. - trace id
- An id returned in a 500 response and written to the server log, so support can find the stack trace.