FastAPI interview question · Most asked
How do you handle errors and customize error responses in FastAPI?
Summary
Raise HTTPException(status_code, detail) for expected errors, define domain exceptions with @app.exception_handler(MyError) to map them to responses, and override RequestValidationError handling to customize 422 payloads.
Longer Answer
Keep domain code framework-agnostic by raising your own exceptions (OrderNotFound) and translating them at the API boundary. A catch-all handler for Exception should log with a request ID and return a generic 500 without internals. Consider RFC 9457 Problem Details as a consistent error format.
Code Example
class OrderNotFound(Exception):
def __init__(self, order_id: int):
self.order_id = order_id
@app.exception_handler(OrderNotFound)
async def order_not_found(request, exc: OrderNotFound):
return JSONResponse(status_code=404, content={"title": "Order not found", "order_id": exc.order_id})
Key Points
HTTPExceptionfor HTTP-level errors- Exception handlers map domain errors
- Custom
RequestValidationErrorhandler - Never leak stack traces
More most-asked FastAPI questions
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?