HTTP error contracts clients can use
Return consistent, safe error responses with request IDs and stable operation IDs.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.
In short
An error contract tells clients exactly what failures look like: which status code, which JSON shape, and which fields they can rely on. Good FastAPI services use the right status codes, return one consistent error body, map internal exceptions to safe messages, and attach a request ID to every response so support can find the logs. Stable OpenAPI operation IDs keep generated clients working as the API evolves.
Explained simply
Things go wrong in every API: bad input, missing permissions, a slow model provider, a bug. Clients cannot avoid errors, but they can handle them well if every error looks the same and means one clear thing.
The status code is the first signal. Codes in the 400s mean the client should change something, like fixing a field or logging in. Codes in the 500s mean the server or something behind it failed, and trying again later might work.
The body gives detail. Pick one JSON shape for every error, with a short title, the status, a stable code a program can check, and a request ID. Never put stack traces, SQL or secret values in it. Those go into your logs, where only your team can see them.
A request ID is a unique label for each request. You send it back in a header and write it in every log line. When a user reports a problem and quotes the ID, you can find exactly what happened in seconds.
Press Play on a diagram to walk through it one step at a time.
- Client input
- 400 malformed request
- 422 failed validation
- 413 body too large
- 415 wrong content type
- Identity and access
- 401 not authenticated
- 403 not allowed
- 404 hide resources of other tenants
- State and limits
- 409 conflict with current state
- 429 quota or rate limit spent
- Server or upstream
- 500 bug in our code
- 502 bad upstream reply
- 503 overloaded or down
- 504 upstream timed out
- Client to Request ID middleware: POST /v1/questions1POST /v1/questions
- Request ID middleware to Route and service: Assign request_id req_8f2c and call route2Assign request_id req_8f2c and call route
- Route and service to Request ID middleware: Unexpected exception raised3Unexpected exception raised
- Request ID middleware to Logs: Log stack trace with request_id req_8f2c4Log stack trace with request_id req_8f2c
- Request ID middleware to Client: 500 problem body and X-Request-ID: req_8f2c5500 problem body and X-Request-ID: req_8f2c
- Client to Logs: Support searches logs for req_8f2c6Support searches logs for req_8f2c
In depth
Picking the right status code
Start with who can fix the problem. Malformed JSON is 400; well-formed data that breaks rules is 422 in FastAPI. A body that is too big is 413, and the wrong media type is 415. Missing or invalid credentials are 401, which should include a WWW-Authenticate header; valid credentials without permission are 403. For a resource that belongs to another tenant, answer 404 so you do not confirm it exists.
State problems get 409 Conflict, for example asking a question on a document that is still processing. Quotas and rate limits get 429 with a Retry-After header. On the server side, 500 means a bug, 502 means an upstream such as the model provider returned something unusable, 503 means you are overloaded or in maintenance, and 504 means an upstream timed out. Accurate codes let clients, proxies and dashboards react correctly without parsing text.
- 401 needs WWW-Authenticate
- 404 instead of 403 across tenants
- 409 for state conflicts
- 429 and 503 with Retry-After
- 502 bad upstream reply, 504 upstream timeout
Shaping validation errors
By default FastAPI answers invalid input with 422 and a body like {"detail": [{"type": "missing", "loc": ["body", "text"], "msg": "Field required", "input": ...}]}. That is useful, but it does not match the rest of your errors, and the input field echoes what the client sent, which may include a password or personal data.
Register a handler for RequestValidationError to reshape it. Build a list from exc.errors() with the field path joined from loc, the error type as a stable code, and the message, and leave out input. Return it inside your standard error body with status 422. Clients can now highlight the exact fields, and every error your API returns, validation or not, has the same top-level shape.
Mapping exceptions to safe messages
Inside services, raise your own exceptions that describe what happened in domain terms: DocumentNotFound, DocumentNotReady, QuotaExceeded, ProviderTimeout. Services should not know about HTTP. At the edge, register one exception handler per type that turns it into a status code and a safe body. HTTPException remains fine for simple cases directly in routes.
Anything you did not plan for is a bug. Catch it at the outermost layer, log the full stack trace with the request ID, and send a generic 500 body: Internal error, plus the request ID. Never forward a provider's raw error text or a database message to clients; it can leak table names, prompts or keys, and it changes whenever the provider changes. Translate upstream failures into your own stable codes such as model_timeout or model_unavailable.
- 1Exception raised
In a route, dependency or service
- 2Known domain error?
Its handler picks status and stable code
- 3Unknown error?
Log stack trace with request ID
- 4Build body
Title, status, code, request ID; no internals
- 5Send response
With X-Request-ID header
Request IDs on every response
Add middleware that runs first for every request. If a trusted proxy already sent an X-Request-ID, reuse it so the ID follows the request across services; otherwise generate a UUID. Check incoming IDs for a sane length and character set, because clients can send anything. Store the ID in a contextvar so every log line in that request can include it, and set it as a response header.
There is one trap. An unhandled exception escapes through call_next in HTTP middleware, and a 500 produced by a catch-all handler is built outside your middleware, so the header can go missing exactly when you need it. Wrap call_next in try and except inside the middleware, log the error there, and build the 500 response yourself. Then put the same ID in error bodies, for example as instance or request_id.
Stable operation IDs and compatibility
Every route in OpenAPI has an operationId. FastAPI generates it from the function name, path and method, giving names like get_document_v1_documents__document_id__get. Client generators turn these into method names, so renaming a Python function or moving a route silently renames methods in every generated client.
Set IDs on purpose. Pass operation_id="getDocument" on a route, or give FastAPI a generate_unique_id_function that builds IDs from the router tag and function name. Then guard them: a test that lists all operation IDs and compares them with a committed file catches accidental changes. The same compatibility rules apply to errors: keep status codes and code values for existing failures, add new codes rather than reusing old ones, and document each code clients may receive.
- Default IDs depend on function name and path
- operation_id=... per route
- generate_unique_id_function for the whole app
- Test that IDs and error codes do not drift
Learn it in 5 short steps
About 30m each. Track them with a timer in your plan.
- 1Pick the right status codes~30m
- 2Shape validation error responses~30m
- 3Map exceptions to safe messages~30m
- 4Add request IDs to every response~30m
- 5Keep OpenAPI operation IDs stable~30m
Key points
- 4xx means the client can fix something; 5xx means the server or an upstream failed.
- Use one error body shape everywhere, for example RFC 9457 problem details with a stable code field.
- Never send stack traces, SQL or provider error text to clients; log them with the request ID instead.
- Return a request ID header on every response, including errors, and include it in logs.
- Set explicit operation IDs so generated client method names do not change when you rename a function.
Key terms
Tap a card to flip it. 0/5 known
Examples
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
class QuotaExceeded(Exception): ...
@app.exception_handler(QuotaExceeded)
async def quota_handler(request: Request, exc: QuotaExceeded) -> JSONResponse:
return JSONResponse(
status_code=429,
media_type="application/problem+json",
headers={"Retry-After": "60"},
content={"type": "https://example.com/errors/quota", "title": "Quota exceeded", "status": 429, "code": "quota_exceeded"},
)A domain exception mapped to a safe, stable problem details response.
Validation errors as problem details
This handler replaces FastAPI's default 422 body. Send {"text": ""} to a route that needs text with min_length=3 and the response has Content-Type application/problem+json, status 422, code validation_failed and an errors list such as {"field": "body.text", "code": "string_too_short"}. The client's input is not echoed back.
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def on_validation(request: Request, exc: RequestValidationError) -> JSONResponse:
errors = [{"field": ".".join(str(p) for p in e["loc"]), "code": e["type"], "message": e["msg"]}
for e in exc.errors()]
return JSONResponse(status_code=422, media_type="application/problem+json", content={
"type": "https://example.com/errors/validation", "title": "Invalid request",
"status": 422, "code": "validation_failed", "errors": errors})Request ID middleware that survives crashes
Every response, including an unexpected 500, carries X-Request-ID, and the stack trace is logged with the same ID. To test it, add a route that raises RuntimeError and call it with curl -i: you should see status 500, a generic body with request_id, the header, and one log line with the traceback and that ID. In production, also validate an incoming ID's length and characters.
import logging, uuid
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app = FastAPI()
log = logging.getLogger("api")
@app.middleware("http")
async def request_id(request: Request, call_next):
rid = request.headers.get("x-request-id") or str(uuid.uuid4())
try:
response = await call_next(request)
except Exception:
log.exception("unhandled error request_id=%s", rid)
response = JSONResponse({"title": "Internal error", "status": 500, "request_id": rid}, status_code=500)
response.headers["X-Request-ID"] = rid
return responseQuick reference
- 4xx: client can fix it. 5xx: server or upstream failed; retry may help.
- 401 not authenticated, 403 not allowed, 404 for other tenants' resources.
- 429 and 503 should include Retry-After.
- 502 bad upstream reply, 504 upstream timed out.
- One error shape everywhere, e.g. RFC 9457: type, title, status, detail, instance + code.
- @app.exception_handler(RequestValidationError) reshapes 422s; drop the echoed input.
- Log stack traces with the request ID; send clients only a generic message.
- Pin operation IDs with operation_id=... or generate_unique_id_function.
Common mistakes
- Returning 200 with an error message in the body, which breaks retries, caching and monitoring.
- Returning 403 for another tenant's document, which confirms that it exists; 404 is safer.
- Letting clients match on the human-readable message instead of a stable code.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Choose a status code for each case: a missing bearer token; text longer than the limit; a document still processing; a user over their daily quota; an unexpected KeyError in a route.
- Exercise 2medium
Create a DocumentNotFound exception raised by a service, and a handler that returns a 404 problem details body with code document_not_found and the document ID in detail.
- Exercise 3hard
Make operation IDs come from the router tag plus the function name, then add a test that fails if any operation ID changes compared with a committed tests/operation_ids.json.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use RFC 9457 problem details?
- It is a good default because it is a published standard with a known media type, application/problem+json. What matters most is using one shape everywhere and adding a stable code field.
- Should I return 200 with success: false?
- No. Use real status codes so clients, proxies, retries and monitoring can tell success from failure without reading the body.
- Can I send the exception message to the client in development?
- You can show more detail behind a debug setting that is off by default, but never enable it in production. Logs are the right place for details.
- Where should the request ID come from?
- Reuse one set by your own proxy or gateway if present, after checking its format; otherwise generate a UUID in the first middleware.