Skip to content

fastapi_tools.exceptions

Custom HTTP exceptions for the webapp.

Classes:

NotAuthenticatedException

NotAuthenticatedException(
    detail: str = "Not authenticated",
)

Bases: HTTPException

Raised when a request requires authentication but none was provided.

Source code in src/fastapi_tools/exceptions.py
def __init__(self, detail: str = "Not authenticated") -> None:  # noqa: D107
    super().__init__(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail=detail,
        headers={"WWW-Authenticate": "Bearer"},
    )

NotAuthorizedException

NotAuthorizedException(detail: str = 'Not authorized')

Bases: HTTPException

Raised when the authenticated user lacks required permissions.

Source code in src/fastapi_tools/exceptions.py
def __init__(self, detail: str = "Not authorized") -> None:  # noqa: D107
    super().__init__(
        status_code=status.HTTP_403_FORBIDDEN,
        detail=detail,
    )

RateLimitExceededException

RateLimitExceededException(
    detail: str = "Rate limit exceeded",
    retry_after: int | None = None,
)

Bases: HTTPException

Raised when a client exceeds the configured rate limit.

Source code in src/fastapi_tools/exceptions.py
def __init__(  # noqa: D107
    self,
    detail: str = "Rate limit exceeded",
    retry_after: int | None = None,
) -> None:
    headers = {}
    if retry_after is not None:
        headers["Retry-After"] = str(retry_after)
    super().__init__(
        status_code=status.HTTP_429_TOO_MANY_REQUESTS,
        detail=detail,
        headers=headers or None,
    )

ServiceUnavailableException

ServiceUnavailableException(
    detail: str = "Service unavailable",
)

Bases: HTTPException

Raised when a downstream service is unavailable.

Source code in src/fastapi_tools/exceptions.py
def __init__(self, detail: str = "Service unavailable") -> None:  # noqa: D107
    super().__init__(
        status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
        detail=detail,
    )

ValidationException

ValidationException(
    detail: str = "Validation error",
    errors: list[dict] | None = None,
)

Bases: HTTPException

Raised for request validation errors.

Source code in src/fastapi_tools/exceptions.py
def __init__(  # noqa: D107
    self,
    detail: str = "Validation error",
    errors: list[dict] | None = None,
) -> None:
    super().__init__(
        status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
        detail={"message": detail, "errors": errors or []},
    )