route_viewset — API Reference
from fastapi_viewsets.decorators.route_viewset import route_viewsetSignature
def route_viewset(
router: APIRouter,
base_path: str,
lifecycle: LifecycleType = "singleton",
pk_field_name: str | None = None,
register_muxws: bool | None = None,
register_rest: bool | None = None,
) -> Callable[[type[T]], type[T]]Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
router | APIRouter | — | FastAPI router to register routes on, for REST and muxws alike; include it in the application |
base_path | str | — | URL prefix for all endpoints |
lifecycle | LifecycleType | "singleton" | Viewset instance lifecycle |
pk_field_name | str | None | None | PK field name; a POST request body leaves it out or gives it as null, any other value answers 422 |
register_muxws | bool | None | None | Whether this viewset's endpoints are published on the muxws transport. None defers to settings.viewsets_register_muxws, itself True by default |
register_rest | bool | None | None | Whether this viewset's endpoints are published on router as HTTP routes. None defers to "yes" |
@transports(rest=..., muxws=...) from fastapi_viewsets.mux_ws decides the same question for a single endpoint. See Choosing which viewsets are published.
Return value
Returns a decorator; the decorator registers the class's routes and returns the class itself. The class is modified in place: it gains a router of its own, carrying every route the viewset serves rebased onto base_path; a FastAPI app that answers GET {base_path}/schema with the viewset's own OpenAPI document; and cls.__viewset_metadata__, a dict of:
| Key | Value |
|---|---|
base_path | the base_path argument |
lifecycle | the lifecycle argument |
router | the APIRouter passed in as the first argument, not the router the class gained |
pk_field_name | the pk_field_name argument, None without it |
paths | each action name, the name of the method serving the endpoint, mapped to its route's path relative to base_path: "" for list_items, "/{pk}" for retrieve, "/bulk" for bulk_create, "/schema" for schema |
A route's path on the application is the routed base path, the include_router prefix followed by base_path, followed by paths[action]. Every endpoint added to router carries __viewset_class__, the class, and __viewset_action__, the action name; the /schema endpoints carry "schema".
Applied as @route_viewset(...) on the class or called as route_viewset(...)(SomeViewSet).
Behaviour
- Collects the
__routereach class in the MRO declares for itself and rebases its routes ontobase_path. - Resolves all generic
TypeVarparameters using the concrete types declared on the viewset class. - Deduplicates routes by HTTP methods plus full path; the most derived class in the MRO wins, so a mixin can replace a route it would otherwise inherit.
- Registers routes most specific first: literal segments such as
bulkandlookup, then{pk}, then the barebase_path; within one path the order isDELETE,PATCH,PUT,POST,GET. - Adds
GET {base_path}/schemaonce per transport, each answering with the OpenAPI document of the endpoints published on that transport. Each operation in it carriesx-viewset-action, the name of the viewset method that serves it (top_ratedforGET {base_path}/top-rated); the FE schema check matches a custom endpoint to a ViewSet method by it. - Derives an OpenAPI tag from the class name (strips
ViewSetsuffix) and records the class's own docstring as that tag's description. - Gives every route a dependency that runs each configured
Middleware'sdepends()before the request body is parsed, plussettings.viewsets_security_schemewhen one is set. That dependency is the last entry of the route'sdependenciesand carries the attribute named byMIDDLEWARE_DEPENDS_ATTRIBUTE("__viewset_middleware_depends__", infastapi_viewsets.decorators.route_viewset) set toTrue. - Drops the declared
response_modelfrom every route when a middleware insettings.viewsets_command_middlewaredeclaresmodifies_response_shape, since that middleware may reshape the body. - Raises
ValueErrorwhenlifecycleis none of"singleton","per-request","instance-key", and when@endpoint_docsnames an endpoint the class does not have. - Adds each endpoint to
routeronce, as a route that matches only the transports it is published on (see muxws); a route not published on REST is left out of the application's OpenAPI document. Records the endpoints published on muxws in the muxws registry. - Runs every configured middleware's
execute()around the call of the viewset method, inside the command middleware chain, unless the action is acelery_viewset_clientmethod, which executes in the worker. - Stores metadata on the class as
cls.__viewset_metadata__.
Lifecycle modes
| Value | Instance creation | State hooks |
|---|---|---|
"singleton" | Once, at decoration time | load_state() / save_state() called on every request. No locking — concurrent requests may race. |
"per-request" | Once per incoming HTTP request | Not called. |
"instance-key" | Once per request | load_state() / save_state() called on every request. No locking — concurrent requests may race. |
See ViewSet Lifecycle for the full guide, including a worked example.
