TL;DR
- HTTP status codes communicate broad protocol outcomes. RFC 9457 Problem Details gives clients a common JSON error shape, and it supersedes RFC 7807.
- Keep the HTTP status authoritative, return
application/problem+json, and use stable problem type URIs for application-specific errors. - FastAPI can centralize handlers for HTTP exceptions, request validation errors, and domain exceptions. Convert internal validation structures into a small, documented extension instead of returning framework internals.
- Do not send stack traces, SQL errors, secrets, or raw request bodies to API clients. Give a safe detail and a correlation identifier for support.
- Publish the error schema in OpenAPI and test content type, headers, status, extensions, and privacy for every error path.
Why clients need a stable error contract
An API client needs more than a status code to recover gracefully. A 409 response might mean a version conflict, a duplicate operation, or a resource state that blocks the requested transition. If one endpoint returns a string, another returns {"error": ...}, and a third returns FastAPI's default validation list, a frontend needs special-case parsing for every route.
RFC 9457, Problem Details for HTTP APIs, defines a common representation for error responses. It obsoletes RFC 7807 while keeping the same widely known core members: type, title, status, detail, and instance. The media type for JSON is application/problem+json. The RFC explicitly says problem details describe the HTTP interface and are not a debugging format. RFC 9457 Problem Details for HTTP APIs
Teams often call the design “RFC 7807 errors” because the earlier RFC introduced it. New implementations should use RFC 9457 as the current specification and preserve compatibility with clients that recognize the former name. You do not need to copy every optional member into every response. Start with a consistent envelope and add extensions only when clients have a clear, documented use for them.
Define the envelope and its semantics
A problem response might look like this:
{
"type": "https://api.example.com/problems/invalid-request",
"title": "The request is invalid",
"status": 422,
"detail": "Correct the listed fields and submit the request again.",
"instance": "urn:request:01J4E7P6KQ8Y4A2F",
"errors": [
{
"pointer": "/items/0/quantity",
"code": "greater_than",
"detail": "Must be greater than zero."
}
]
}
The type URI identifies the category of problem and should remain stable. Use a resolvable documentation URL for errors clients need to understand. The title is a short summary. The status repeats the HTTP status for convenience, but the actual HTTP response status must match it. The detail describes this occurrence in human-readable terms and should help the client correct the request without disclosing implementation detail. The instance identifies this particular occurrence, often with an opaque request ID.
RFC 9457 says clients should treat type as the primary identifier and should not parse detail to obtain machine-readable data. Put stable codes in extensions such as errors[].code. Keep extension names documented and consistent. A frontend can branch on the type URI or an explicit code while showing the detail as text.
Do not include a bespoke code or message top-level field if it creates a competing interpretation of the standard members. If your existing clients already use those fields, migrate deliberately by adding an extension or versioning the contract. Avoid extensions that leak a database table, Python exception name, stack trace, token, or internal hostname.
Implement a small Problem model in FastAPI
Keep problem creation centralized. The model below limits the shape of errors returned by application handlers and keeps the server's HTTP status separate from a client-controlled body.
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Problem(Exception):
status: int
type_uri: str
title: str
detail: str
extensions: dict[str, Any] = field(default_factory=dict)
def __post_init__(self) -> None:
super().__init__(self.title)
Define application exception types for expected business conditions. For example, a duplicate external reference can map to a 409 conflict problem. Authentication failures map to 401 with the appropriate WWW-Authenticate header. Rate limits can include Retry-After when a meaningful retry time is known. The problem body should supplement HTTP semantics, not replace them.
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
def problem_response(request: Request, problem: Problem, headers=None):
route = request.scope.get("route")
template = getattr(route, "path", None) or "/unknown"
request_id = getattr(request.state, "request_id", "unknown")
body = {
"type": problem.type_uri,
"title": problem.title,
"status": problem.status,
"detail": problem.detail,
"instance": f"urn:request:{request_id}",
**problem.extensions,
}
return JSONResponse(
status_code=problem.status,
content=body,
media_type="application/problem+json",
headers=headers,
)
@app.exception_handler(Problem)
async def handle_problem(request: Request, exc: Problem):
return problem_response(request, exc)
In a production implementation, validate extension keys so callers cannot overwrite type, title, status, detail, or instance. The example's route template variable is included to show how to avoid echoing a raw path containing user-controlled identifiers; it is not put into the response. Ensure the request ID is generated by trusted middleware and is safe to expose. Use a fallback occurrence identifier if middleware did not run.
FastAPI allows custom exception handlers and specifically documents overriding its defaults for HTTP exceptions and request validation errors. Use Starlette's HTTPException base class in the handler when you want to catch exceptions raised by Starlette components too. FastAPI exception handling documentation
Map HTTP exceptions without losing protocol headers
When translating HTTPException, preserve its status and headers. Dropping headers can break authentication challenges or retry behavior even if the JSON body looks consistent. Avoid exposing arbitrary exception details if they contain data from an upstream service or internal implementation.
from starlette.exceptions import HTTPException as StarletteHTTPException
HTTP_TITLES = {
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
409: "Conflict",
422: "Unprocessable Content",
429: "Too Many Requests",
}
@app.exception_handler(StarletteHTTPException)
async def handle_http_exception(request: Request, exc: StarletteHTTPException):
title = HTTP_TITLES.get(exc.status_code, "Request Failed")
safe_detail = public_http_detail(exc.status_code, exc.detail)
problem = Problem(
status=exc.status_code,
type_uri=problem_type_for_status(exc.status_code),
title=title,
detail=safe_detail,
)
return problem_response(request, problem, headers=exc.headers)
public_http_detail should use a reviewed mapping for expected errors, not stringify arbitrary exception objects. For a generic 500, return a neutral explanation and a request identifier. Log the internal exception in a protected log pipeline with the same correlation ID. Never return a Python traceback, database constraint name, internal URL, or provider response body.
Turn validation errors into a stable extension
FastAPI's request validation errors include structured location and error information. Those are useful internally, but returning them unchanged couples the API to a framework and may expose rejected input. Transform them into a documented extension with a stable code and a JSON Pointer location when a body field is involved.
JSON Pointer encodes a reference token by replacing ~ with ~0 and / with ~1. Validation locations may include path, query, header, or body segments that do not map directly to a JSON document. Preserve the source separately and include a pointer only for a body location.
from fastapi.exceptions import RequestValidationError
def pointer_escape(value: object) -> str:
return str(value).replace("~", "~0").replace("/", "~1")
def public_validation_errors(exc: RequestValidationError) -> list[dict[str, str]]:
result = []
for error in exc.errors():
loc = list(error.get("loc", ()))
source = str(loc[0]) if loc else "request"
parts = loc[1:] if source == "body" else loc
item = {
"source": source,
"code": map_validation_code(str(error.get("type", "invalid"))),
"detail": safe_validation_message(str(error.get("type", "invalid"))),
}
if source == "body":
item["pointer"] = "".join("/" + pointer_escape(part) for part in parts)
result.append(item)
return result
@app.exception_handler(RequestValidationError)
async def handle_validation_error(request: Request, exc: RequestValidationError):
problem = Problem(
status=422,
type_uri="https://api.example.com/problems/invalid-request",
title="The request is invalid",
detail="Correct the listed fields and submit the request again.",
extensions={"errors": public_validation_errors(exc)},
)
return problem_response(request, problem)
The mapping functions should use an allowlisted vocabulary. Pydantic's internal error type can change across major versions, so map known types into your own stable code set and provide a safe fallback. Do not include error["input"], context objects, or raw body content by default. FastAPI's documentation shows that the validation exception contains the received body and can be used for debugging; that does not mean it should be exposed to an API caller. FastAPI request validation error details
Document problem responses in OpenAPI
A consistent wire format is only useful if clients can discover it. Define a reusable Pydantic response model for the standard members and your chosen extensions. Add it to route response declarations for expected 4xx and 5xx outcomes. FastAPI's responses parameter can document additional responses, but custom exception handlers do not automatically make every endpoint's OpenAPI declaration complete.
from pydantic import BaseModel, ConfigDict
class FieldIssue(BaseModel):
source: str
code: str
detail: str
pointer: str | None = None
class ProblemDocument(BaseModel):
model_config = ConfigDict(extra="allow")
type: str
title: str
status: int
detail: str
instance: str
@app.post(
"/orders",
responses={
409: {"model": ProblemDocument, "description": "Order conflicts with current state"},
422: {"model": ProblemDocument, "description": "Request validation failed"},
},
)
async def create_order(...):
...
Set the documented media type to application/problem+json in your OpenAPI response content. Include representative examples with stable problem type URIs. If clients use a generated SDK, regenerate it and test that its error parser recognizes the content type and exposes extension data. A generic JSON schema without the media type can cause clients to treat problems as ordinary success payloads.
Keep privacy and security part of the contract
Error messages should help a caller fix a request without revealing internals. A validation error can say that a field is missing or outside an accepted range. It should not repeat a password, token, credit card number, or full invalid body. A database conflict can use a stable application code without naming a table or constraint. An unexpected exception should return a generic problem and correlation ID.
Problem type URIs are identifiers, not authorization tokens. Clients should not automatically dereference them in a way that creates an SSRF or tracking risk. Publish documentation for types you expect clients and operators to understand, and keep those pages stable. Do not encode customer IDs or secret values in the URI or instance.
Choose whether validation failures use 400 or 422 and keep the behavior consistent. The important point is to preserve the status semantics for generic HTTP software and align the body status with the actual response. If the API supports localization, translate human-facing title and detail while keeping type URIs and machine codes stable.
Test every error path as a client would see it
Test the response at the HTTP boundary, not only the helper function. For validation, assert the content type, status, pointer escaping, source, and absence of raw input. For authentication, verify the WWW-Authenticate header is preserved. For rate limits, test Retry-After where it applies. For internal errors, assert that the response omits stack traces and database messages while the protected logs retain a correlation identifier.
- Send malformed JSON and an invalid body field. Confirm both responses use the same problem media type and documented envelope.
- Raise an application domain exception and a Starlette HTTP exception. Confirm the correct handler runs and headers survive.
- Cause an unhandled exception. Confirm the client receives a generic 500 problem and cannot see the stack trace.
- Include a sentinel secret in invalid request data. Confirm it appears in neither the response nor unprotected logs.
- Validate generated OpenAPI output contains the error media type, status, schema, and examples for documented routes.
- Test proxies or gateways that can modify status or content. Ensure monitoring detects a mismatch between the HTTP status and the body member.
API consumers should key on the problem type or stable extension code, not parse the detail text. If a problem changes in a backward-incompatible way, introduce a new type or versioned contract. For larger interfaces, consider a common API version policy such as dated API versions in FastAPI.
Frequently asked questions
Should a new FastAPI API use RFC 7807 or RFC 9457?
Use RFC 9457, the current specification for Problem Details. It obsoletes RFC 7807 and retains the familiar problem object. Teams can describe the format as “RFC 7807-style” for discoverability, but new documentation should cite RFC 9457 and its current media type and security guidance.
Should the error code go in the problem type or an extension field?
Use the stable type URI as the primary identifier for a category of problem. Add a documented extension such as errors[].code for field-level or subcategory codes. Keep human-readable detail out of client branching logic because it can change or be localized.
Can I return FastAPI's validation error object directly?
You can override the validation handler, but returning framework error structures unchanged couples the public contract to framework internals and may expose rejected input. Map errors into your own stable codes and safe messages, and include only the field locations clients need to fix a request.
Should production 500 responses include the exception detail?
No. Return a generic problem detail and an opaque occurrence or request identifier. Keep stack traces and internal exception data in an access-controlled logging system. This helps support correlate a report without disclosing implementation information to an API caller.
Make the error contract predictable and safe
Problem Details gives an API a common response shape, but consistency depends on centralized handlers, stable type URIs, preserved HTTP headers, and documented extensions. FastAPI's exception system can translate validation, HTTP, and domain errors into that contract while keeping internal diagnostic information in protected logs.
If your API clients are handling different error shapes across endpoints, talk with our engineering team about a migration plan, OpenAPI contract, and privacy-safe error boundary.
