Skip to main content

APIRouter

APIRouter class, used to group path operations, for example to structure an app in multiple files. It would then be included in the FastAPI app, or in another APIRouter (ultimately included in the app).

Attributes​

AttributeTypeDescription
prefixstr = ""An optional path prefix for the router.
tags`list[strEnum]` = []
dependencieslist[params.Depends] = []A list of dependencies (using Depends()) to be applied to all the path operations in this router.
deprecated`boolNone` = null
include_in_schemabool = trueTo include (or not) all the path operations in this router in the generated OpenAPI.
responses`dict[intstr, dict[str, Any]]` = {}
callbackslist[BaseRoute] = []OpenAPI callbacks that should apply to all path operations in this router.
dependency_overrides_provider`AnyNone` = null
route_classtype[[APIRoute](apiroute.md?sid=fastapi_routing_apiroute)] = APIRouteCustom route (path operation) class to be used by this router.
default_response_classtype[[Response](../openapi/models/response.md?sid=fastapi_openapi_models_response)] = JSONResponseThe default response class to be used.
generate_unique_id_functionCallable[[[APIRoute](apiroute.md?sid=fastapi_routing_apiroute)], str] = generate_unique_idCustomize the function used to generate unique IDs for the path operations shown in the generated OpenAPI.
strict_content_typebool = trueEnable strict checking for request Content-Type headers.
on_startuplist[Callable[[], Any]] = []A list of startup event handler functions.
on_shutdownlist[Callable[[], Any]] = []A list of shutdown event handler functions.
lifespan_contextLifespan[Any] = nullThe resolved lifespan context manager used to handle startup and shutdown events.

Constructor​

Signature​

def APIRouter(
prefix: str = "",
tags: list[str | Enum]| None = null,
dependencies: Sequence[params.Depends]| None = null,
default_response_class: type[[Response](../openapi/models/response.md?sid=fastapi_openapi_models_response)] = JSONResponse,
responses: dict[int | str, dict[str, Any]]| None = null,
callbacks: list[BaseRoute]| None = null,
routes: list[BaseRoute]| None = null,
redirect_slashes: bool = true,
default: ASGIApp | None = null,
dependency_overrides_provider: Any | None = null,
route_class: type[[APIRoute](apiroute.md?sid=fastapi_routing_apiroute)] = APIRoute,
on_startup: Sequence[Callable[[], Any]]| None = null,
on_shutdown: Sequence[Callable[[], Any]]| None = null,
lifespan: Lifespan[Any]| None = null,
deprecated: bool | None = null,
include_in_schema: bool = true,
generate_unique_id_function: Callable[[[APIRoute](apiroute.md?sid=fastapi_routing_apiroute)], str] = generate_unique_id,
strict_content_type: bool = true
) - > null

Parameters​

NameTypeDescription
prefixstr = ""An optional path prefix for the router (e.g., '/users').
tags`list[strEnum]
dependencies`Sequence[params.Depends]None` = null
default_response_classtype[[Response](../openapi/models/response.md?sid=fastapi_openapi_models_response)] = JSONResponseThe default response class to be used for path operations.
responses`dict[intstr, dict[str, Any]]
callbacks`list[BaseRoute]None` = null
routes`list[BaseRoute]None` = null
redirect_slashesbool = trueWhether to detect and redirect slashes in URLs when the client format differs.
default`ASGIAppNone` = null
dependency_overrides_provider`AnyNone` = null
route_classtype[[APIRoute](apiroute.md?sid=fastapi_routing_apiroute)] = APIRouteCustom route class to be used by this router for path operations.
on_startup`Sequence[Callable[[], Any]]None` = null
on_shutdown`Sequence[Callable[[], Any]]None` = null
lifespan`Lifespan[Any]None` = null
deprecated`boolNone` = null
include_in_schemabool = trueWhether to include the path operations of this router in the generated OpenAPI schema.
generate_unique_id_functionCallable[[[APIRoute](apiroute.md?sid=fastapi_routing_apiroute)], str] = generate_unique_idFunction used to generate unique IDs for path operations in OpenAPI.
strict_content_typebool = trueIf True, requires a Content-Type header for request bodies to be parsed as JSON.

Signature​

def APIRouter(
prefix: str = "",
tags: list[str | Enum]| None = null
) - > null

Parameters​

NameTypeDescription
prefixstr = ""An optional path prefix that will be prepended to all routes in this router.
tags`list[strEnum]

Methods​


route()​

@classmethod
def route(
path: str,
methods: Collection[str]| None = null
) - > Callable

Registers a generic route with the router using a decorator pattern.

Parameters​

NameTypeDescription
pathstrThe URL path for the route.
methods`Collection[str]None` = null

Returns​

TypeDescription
CallableA decorator function that registers the decorated endpoint to the specified path.

add_api_route()​

@classmethod
def add_api_route(
path: str,
endpoint: Callable
) - > null

Adds a new API path operation to the router, configuring its endpoint, response models, and metadata.

Parameters​

NameTypeDescription
pathstrThe URL path for the API endpoint.
endpointCallableThe function to be called when the route is accessed.

Returns​

TypeDescription
nullnull

websocket()​

@classmethod
def websocket(
path: str
) - > Callable

Decorate a WebSocket function.

Parameters​

NameTypeDescription
pathstrThe WebSocket URL path.

Returns​

TypeDescription
CallableA decorator that registers the function as a WebSocket endpoint.

include_router()​

@classmethod
def include_router(
router: [APIRouter](apirouter.md?sid=fastapi_routing_apirouter)
) - > null

Include another APIRouter in the same current APIRouter.

Parameters​

NameTypeDescription
router[APIRouter](apirouter.md?sid=fastapi_routing_apirouter)The sub-router instance to be merged into the current router.

Returns​

TypeDescription
nullnull

get()​

@classmethod
def get(
path: str
) - > Callable

Add a path operation using an HTTP GET operation.

Parameters​

NameTypeDescription
pathstrThe URL path for the GET operation.

Returns​

TypeDescription
CallableA decorator to register a GET request handler.

post()​

@classmethod
def post(
path: str
) - > Callable

Add a path operation using an HTTP POST operation.

Parameters​

NameTypeDescription
pathstrThe URL path for the POST operation.

Returns​

TypeDescription
CallableA decorator to register a POST request handler.

put()​

@classmethod
def put(
path: str
) - > Callable

Add a path operation using an HTTP PUT operation.

Parameters​

NameTypeDescription
pathstrThe URL path for the PUT operation.

Returns​

TypeDescription
CallableA decorator to register a PUT request handler.

delete()​

@classmethod
def delete(
path: str
) - > Callable

Add a path operation using an HTTP DELETE operation.

Parameters​

NameTypeDescription
pathstrThe URL path for the DELETE operation.

Returns​

TypeDescription
CallableA decorator to register a DELETE request handler.

patch()​

@classmethod
def patch(
path: str
) - > Callable

Add a path operation using an HTTP PATCH operation.

Parameters​

NameTypeDescription
pathstrThe URL path for the PATCH operation.

Returns​

TypeDescription
CallableA decorator to register a PATCH request handler.

add_event_handler()​

@classmethod
def add_event_handler(
event_type: str,
func: Callable
) - > null

Add an event handler function for startup or shutdown.

Parameters​

NameTypeDescription
event_typestrThe type of event to handle, either 'startup' or 'shutdown'.
funcCallableThe callback function to execute when the event occurs.

Returns​

TypeDescription
nullnull

on_event()​

@classmethod
def on_event(
event_type: str
) - > Callable

Add an event handler for the router.

Parameters​

NameTypeDescription
event_typestrThe type of event, such as 'startup' or 'shutdown'.

Returns​

TypeDescription
CallableA decorator that registers the function as an event handler for the specified event type.