Skip to content

Reference: decorator

The public symbols of the decorator layer:

from fastapi_typed_errors import Raises, with_errors

with_errors

fastapi_typed_errors.with_errors

with_errors(router: R, /, *, auto: bool = False) -> R

Enable Raises handling on the router and return the same router.

The router's add_api_route is replaced (on the instance) with a wrapper that reads Raises markers from the endpoint's return annotation and fills responses={} accordingly. Every registration path — the 8 HTTP verb decorators, api_route and imperative add_api_route calls, on the router or on the application — funnels into that single method, so nothing else needs patching. The object identity is preserved: include_router, websockets and OpenAPI work exactly as without the patch. Idempotent: wrapping twice is a no-op.

For an application, wrap its router: with_errors(app.router).

Parameters:

Name Type Description Default
router R

The router to enable Raises handling on.

required
auto bool

When True, also fill responses from errors discovered by statically walking each endpoint and its whole dependency tree — no Raises[...] needed; discovered errors are merged with any that are declared. Set it on the first with_errors call; because wrapping is idempotent, a later call does not change it.

False

Returns:

Name Type Description
R R

The same router instance, for chaining and assignment.

Raises

fastapi_typed_errors.Raises

Raises(*errors: type[BaseError[Any]])

Marker listing the errors a route can raise, for Annotated return metadata.

The wrapper created by with_errors() reads this marker at registration time and fills the route's responses={} accordingly. The marker itself is inert: pydantic and FastAPI ignore it, so the success schema stays clean.

Both spellings are equivalent; the constructor form is handy for shared tuples of errors::

def get_item(item_id: int) -> Annotated[Item, Raises[NotFoundError, ForbiddenError]]: ...
def get_user(user_id: int) -> Annotated[User, Raises(*TOKEN_ERRORS)]: ...

Attributes:

Name Type Description
errors tuple[type[BaseError[Any]], ...]

The declared error classes, in declaration order.

Validate and store the declared error classes.

Parameters:

Name Type Description Default
*errors type[BaseError[Any]]

BaseError subclasses with a declared code and status.

()

Raises:

Type Description
TypeError

If no classes are given, a member is not a BaseError subclass, or a member lacks a declared error_code / http_status.