QuickDevGuide

Home › FastAPI

Error Handling — FastAPI

Raise HTTPException(statuscode, detail) to return an error. Add @app.exceptionhandler(...) to map your own exceptions, or to change the shape of validation errors. Situation Response Not found raise HTTPException(404, "Item not found") Auth missing HTTPException(401, headers={"WWW-Authenticate": "Bearer"}) Domain rule broken custom exception → 409 / 422 via a handler Invalid request RequestValidationError → 422 (customisable) Keep error bodies consistent ({"error": ..., "detail": ...}) so clients can handle them generically.

Key Takeaways