One Error Shape for the Whole API
Every error an API sends can have one JSON shape, modeled on RFC 9457's problem details (a status, a title, a detail sentence and, on a 422, a list of field problems), built by one problem() function and sent by an exception handler for each kind of error, FastAPI's own 404 and 422 included, with a catch-all that answers a crash with a calm 500 and never a traceback.
Journeyman · FastAPI · REST API · Updated
After this lesson you can
- Describe the API's one error shape, with its status, title, detail and problems, and build it with HTTPStatus and a problem() function
- Reshape FastAPI's 404 and 422 into the one error shape with exception handlers, and answer every crash with a 500 that hides the traceback
Key takeaways
- Out of the box, a FastAPI error's detail is a sentence for one error, a list for a 422, and a crash isn't JSON at all, so a caller has to handle each one differently.
- This course's one error shape has status, title and detail, plus problems on a 422, each a field and a message. It's modeled on RFC 9457's problem details.
- A handler for Starlette's HTTPException reshapes every HTTPException, FastAPI's own 404 for an unknown address included. A handler for RequestValidationError reshapes the 422.
- A catch-all handler for Exception answers every crash with a 500 and one calm sentence. The whole error still goes to the server's terminal, where you can read it.
- Never send a traceback or an exception's own message to a caller. It shows your folders and code to anyone who asks.
The phone app or web page that calls your API has to show something when a call goes wrong. Its developer writes that code once, for the error answers you told them about; any other answer turns into a blank screen or a crash on their side. Errors that all look the same are what make an API something other people can build on.
Spoke & Chain's tickets API, from Raising Your Own Exceptions in an API, has a new route too: GET /archive reads the shop's old tickets from archive.json, a file that didn't come along when the shop moved its server to a new laptop.
Three shapes for one job
Here's how the API answers three requests that go wrong, each answer's status line and body:
GET /tickets/99
404 Not Found
{"detail":"There's no ticket 99."}
POST /tickets {"customer": "Lena", "bike": 7}
422 Unprocessable Content
{"detail":[{"type":"string_type","loc":["body","bike"],"msg":"Input should be a valid string","input":7},{"type":"missing","loc":["body","problem"],"msg":"Field required","input":{"customer":"Lena","bike":7}}]}
GET /archive
500 Internal Server Error
Internal Server Error
The front desk's app reads detail and shows it. For the 404, detail is a sentence. For the 422, it's a list. And the crash isn't JSON at all, so the app fails to read it. Three answers, three pieces of code on the other side.
One shape for every error
A standard, RFC 9457, Problem Details for HTTP APIs, names the parts most APIs agree on. This course's shape borrows three of them and adds a list for field problems:
status: the status code, as a number, the same as the answer's own, so it survives when the body is saved or logged.title: the status code's name, such as"Not Found".detail: what went wrong this time, always a sentence a person can read.problems: only on a 422, one{"field": ..., "message": ...}for each thing that's wrong, in order.
From here on, every error this course's APIs send has this shape. It replaces the {"detail": ...} bodies FastAPI has sent so far: detail stays, now always a sentence, and status, title and, on a 422, problems come with it.
The title needs no list of your own. Python's http module knows every code's name:
from http import HTTPStatus
print(HTTPStatus(404).phrase)
print(HTTPStatus(409).phrase)
Not Found
Conflict
(Python 3.13 and later name 422 Unprocessable Content; Python 3.12 still uses its older name, Unprocessable Entity.) One function builds every error answer:
from http import HTTPStatus
from fastapi.responses import JSONResponse
def problem(status, detail, problems=None, headers=None):
body = {"status": status, "title": HTTPStatus(status).phrase, "detail": detail}
if problems is not None:
body["problems"] = problems
return JSONResponse(status_code=status, content=body, headers=headers)
headers passes on any headers an error carries; the 401 in Tokens: Signing In with a JWT has one. The two handlers from the last lesson become return problem(404, str(exc)) and return problem(409, str(exc)).
Handlers for FastAPI's own errors
FastAPI raises two exceptions of its own, and each gets a handler:
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(StarletteHTTPException)
def http_error(request: Request, exc: StarletteHTTPException):
return problem(exc.status_code, exc.detail, headers=exc.headers)
@app.exception_handler(RequestValidationError)
def validation_error(request: Request, exc: RequestValidationError):
problems = []
for error in exc.errors():
problems.append({"field": error["loc"][-1], "message": error["msg"]})
return problem(422, "The request isn't valid.", problems)
HTTPExceptionis what a route raises, and what FastAPI raises for an address no route answers, such as/bikes. FastAPI is built on a toolkit named Starlette, and FastAPI'sHTTPExceptionis a kind of Starlette's, so a handler for Starlette's catches both.as StarletteHTTPExceptionrenames it as it's imported, so the two names don't clash.RequestValidationErroris raised before the route runs, when a request breaks the rules.exc.errors()is the list from Reading FastAPI's 422 Validation Errors. Each error's field is the last item of itsloc("bike"from["body", "bike"]), and its message is itsmsg.
A crash never shows its traceback
GET /archive crashes because archive.json isn't there. FastAPI's plain-text Internal Server Error keeps the details back. Turn on FastAPI(debug=True), and the caller gets the whole traceback instead: every function that was running, with your folders and code, ending in FileNotFoundError: [Errno 2] No such file or directory: 'archive.json'. That's a map of your server for anyone who asks, so never on a server others can reach. A catch-all handler, for Exception itself, gives every crash the one shape:
@app.exception_handler(Exception)
def server_error(request: Request, exc: Exception):
return problem(500, "Something went wrong on our side.")
It doesn't send str(exc), which would give away the file's name. The most specific handler wins, so a TicketNotFound still gets its 404. And the whole error still appears in the server's terminal, starting ERROR: Exception in ASGI application, where you'll read it.

The same three requests, and two more, now answer:
GET /tickets/99
404 Not Found
{"status":404,"title":"Not Found","detail":"There's no ticket 99."}
PATCH /tickets/1/status {"status": "ready"}
409 Conflict
{"status":409,"title":"Conflict","detail":"Ticket 1 is waiting, so it can't go to ready."}
POST /tickets {"customer": "Lena", "bike": 7}
422 Unprocessable Content
{"status":422,"title":"Unprocessable Content","detail":"The request isn't valid.","problems":[{"field":"bike","message":"Input should be a valid string"},{"field":"problem","message":"Field required"}]}
GET /bikes
404 Not Found
{"status":404,"title":"Not Found","detail":"Not Found"}
GET /archive
500 Internal Server Error
{"status":500,"title":"Internal Server Error","detail":"Something went wrong on our side."}
Do it: build the body of an error answer
Write the part of problem() that builds the body, from the list FastAPI's 422 hands over.
status: the status code, such as404.detail: the sentence for this error, such as"There's no ticket 99.".errors: FastAPI's error list for a 422, each a dictionary with"type","loc"and"msg"; orNone(the default) for any other error.
Your job: write problem_body(status, detail, errors=None), which returns a dictionary with:
"status":status;"title":HTTPStatus(status).phrase;"detail":detail.- Only when
errorsisn'tNone,"problems": one{"field": ..., "message": ...}for each error, in order, wherefieldis the last item of the error'slocandmessageis itsmsg. An empty list gives"problems": [].
Worked through: problem_body(404, "There's no ticket 99.") returns {"status": 404, "title": "Not Found", "detail": "There's no ticket 99."}, with no "problems". And for one error, [{"type": "missing", "loc": ["body", "problem"], "msg": "Field required"}], problem_body(422, "The request isn't valid.", errors) returns {"status": 422, "title": "Unprocessable Content", "detail": "The request isn't valid.", "problems": [{"field": "problem", "message": "Field required"}]}.
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
One error shape means a caller writes its error handling once, and a catch-all that answers calmly while the terminal keeps the details means a bug in your code never becomes a map of your server.