Sobes.tech
Middle

How do you implement error handling in FastAPI and return correct HTTP statuses?

sobes.tech AI

Answer from AI

In FastAPI, error handling can be implemented using exceptions and exception handlers. The HTTPException class is used to return correct HTTP statuses.

Example of handling an error and returning a 404 status:

from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo item"}

@app.get("/items/{item_id}")
async def read_item(item_id: str):
    if item_id not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": items[item_id]}

For more complex errors, you can create custom exceptions and register handlers:

from fastapi import Request
from fastapi.responses import JSONResponse

class MyCustomError(Exception):
    def __init__(self, name: str):
        self.name = name

@app.exception_handler(MyCustomError)
async def custom_exception_handler(request: Request, exc: MyCustomError):
    return JSONResponse(
        status_code=400,
        content={"message": f"Error: {exc.name}"},
    )

@app.get("/error")
async def error_endpoint():
    raise MyCustomError(name="Something went wrong")

Thus, errors can be handled centrally, and understandable HTTP statuses and messages can be returned to the client.