Skip to content

route_viewset — API Reference ​

python
from fastapi_viewsets.decorators.route_viewset import route_viewset

Signature ​

python
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 ​

ParameterTypeDefaultDescription
routerAPIRouter—FastAPI router to register routes on, for REST and muxws alike; include it in the application
base_pathstr—URL prefix for all endpoints
lifecycleLifecycleType"singleton"Viewset instance lifecycle
pk_field_namestr | NoneNonePK field name; a POST request body leaves it out or gives it as null, any other value answers 422
register_muxwsbool | NoneNoneWhether this viewset's endpoints are published on the muxws transport. None defers to settings.viewsets_register_muxws, itself True by default
register_restbool | NoneNoneWhether 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:

KeyValue
base_paththe base_path argument
lifecyclethe lifecycle argument
routerthe APIRouter passed in as the first argument, not the router the class gained
pk_field_namethe pk_field_name argument, None without it
pathseach 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 __router each class in the MRO declares for itself and rebases its routes onto base_path.
  • Resolves all generic TypeVar parameters 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 bulk and lookup, then {pk}, then the bare base_path; within one path the order is DELETE, PATCH, PUT, POST, GET.
  • Adds GET {base_path}/schema once per transport, each answering with the OpenAPI document of the endpoints published on that transport. Each operation in it carries x-viewset-action, the name of the viewset method that serves it (top_rated for GET {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 ViewSet suffix) and records the class's own docstring as that tag's description.
  • Gives every route a dependency that runs each configured Middleware's depends() before the request body is parsed, plus settings.viewsets_security_scheme when one is set. That dependency is the last entry of the route's dependencies and carries the attribute named by MIDDLEWARE_DEPENDS_ATTRIBUTE ("__viewset_middleware_depends__", in fastapi_viewsets.decorators.route_viewset) set to True.
  • Drops the declared response_model from every route when a middleware in settings.viewsets_command_middleware declares modifies_response_shape, since that middleware may reshape the body.
  • Raises ValueError when lifecycle is none of "singleton", "per-request", "instance-key", and when @endpoint_docs names an endpoint the class does not have.
  • Adds each endpoint to router once, 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 a celery_viewset_client method, which executes in the worker.
  • Stores metadata on the class as cls.__viewset_metadata__.

Lifecycle modes ​

ValueInstance creationState hooks
"singleton"Once, at decoration timeload_state() / save_state() called on every request. No locking — concurrent requests may race.
"per-request"Once per incoming HTTP requestNot called.
"instance-key"Once per requestload_state() / save_state() called on every request. No locking — concurrent requests may race.

See ViewSet Lifecycle for the full guide, including a worked example.

Released under the MIT License.