How to Return Custom Error Response in FastAPI
In FastAPI, you can return a custom error response by raising
HTTPException with a specific status_code and detail message. You can also customize the error response by creating your own exception handler or returning a JSONResponse with your custom content.Syntax
To return a custom error response in FastAPI, use the HTTPException class from fastapi. You specify the status_code for the HTTP error and a detail message describing the error.
Optionally, you can create a custom exception handler to control the full response format.
python
from fastapi import HTTPException raise HTTPException(status_code=404, detail="Item not found")
Example
This example shows a FastAPI app with a route that raises a custom 404 error using HTTPException. The client receives a JSON response with the status code and detail message.
python
from fastapi import FastAPI, HTTPException from fastapi.responses import JSONResponse from fastapi.requests import Request from fastapi.exceptions import HTTPException app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id != 42: raise HTTPException(status_code=404, detail="Item not found") return {"item_id": item_id, "name": "The Answer"} # Custom exception handler example @app.exception_handler(HTTPException) async def custom_http_exception_handler(request: Request, exc: HTTPException): return JSONResponse( status_code=exc.status_code, content={"error": True, "message": exc.detail} )
Output
Request: GET /items/1
Response: 404
{
"error": true,
"message": "Item not found"
}
Request: GET /items/42
Response: 200
{
"item_id": 42,
"name": "The Answer"
}
Common Pitfalls
- Not raising
HTTPExceptionproperly will cause FastAPI to return a default 500 error instead of your custom message. - Returning a plain dictionary instead of raising an exception will result in a 200 OK status, which is misleading for errors.
- For full control over the error response format, you must use a custom exception handler; otherwise, FastAPI uses its default JSON error format.
python
from fastapi import FastAPI app = FastAPI() # Wrong: returns 200 OK with error message @app.get("/wrong") async def wrong_error(): return {"error": "Not found"} # Right: raises HTTPException with 404 status from fastapi import HTTPException @app.get("/right") async def right_error(): raise HTTPException(status_code=404, detail="Not found")
Quick Reference
Use this quick guide to return custom errors in FastAPI:
- Raise HTTPException:
raise HTTPException(status_code=400, detail="Error message") - Custom handler: Use
@app.exception_handler(HTTPException)to customize response format - Return JSONResponse: For full control, return
JSONResponse(status_code=..., content={...})
Key Takeaways
Raise HTTPException with status_code and detail to send custom error responses.
Use custom exception handlers to fully control error response format.
Avoid returning error messages with 200 status; always raise exceptions for errors.
JSONResponse can be used for custom error content and status codes.
FastAPI automatically converts HTTPException to JSON error responses.