Reference

Exceptions

ClassModuleSummary
EndpointContextfastapi.exceptions—
HTTPExceptionfastapi.exceptionsAn HTTP exception you can raise in your own code to show errors to the client.
WebSocketExceptionfastapi.exceptionsA WebSocket exception you can raise in your own code to show errors to the client.
FastAPIErrorfastapi.exceptionsA generic, FastAPI-specific error.
DependencyScopeErrorfastapi.exceptionsA dependency declared that it depends on another dependency with an invalid
ValidationExceptionfastapi.exceptions—
RequestValidationErrorfastapi.exceptions—
WebSocketRequestValidationErrorfastapi.exceptions—
ResponseValidationErrorfastapi.exceptions—
PydanticV1NotSupportedErrorfastapi.exceptionsA pydantic.v1 model is used, which is no longer supported.
FastAPIDeprecationWarningfastapi.exceptionsA custom deprecation warning as DeprecationWarning is ignored

Raising an HTTP error

from fastapi import FastAPI, HTTPException

app = FastAPI()


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id < 0:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

Custom exception handlers

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse({"detail": exc.detail}, status_code=exc.status_code)