Views
API Reference: Views¶
The view layer is the core of request handling in SRF. GenericAPIView handles action dispatch, schema validation, permissions, filtering, and pagination, while several CRUD mixins combine into ready-to-use ViewSets. For mechanism details and complete examples, see ViewSet and Actions and Decorators.
Action dispatch¶
as_view(actions) maps HTTP methods to view methods. Usually SanicRouter.register() builds the mapping automatically; you only need to pass it yourself when calling app.add_route() manually:
from sanic import Sanic
from srf.views import BaseViewSet
app = Sanic("demo")
class BookViewSet(BaseViewSet):
queryset = Book.all() # Tortoise QuerySet
schema = BookSchema # Pydantic model
app.add_route(
BookViewSet.as_view({"get": "list", "post": "create"}),
"/books",
)
The keys of actions are lowercase HTTP methods and the values are the method names to call. Methods not present in the mapping are not registered as routes; if the corresponding method cannot be resolved at runtime, 405 Method Not Allowed is raised.
PUT and PATCH
Currently both put and patch map to update, and update validates the request body against the full schema. The semantic distinction between the two (full update / partial update) has not been implemented yet.
View base classes¶
GenericAPIView is the common base class for all views; the other three composite classes simply pre-assemble the CRUD mixins.
GenericAPIView ¶
Bases: HTTPMethodView
Base class for all SRF views: schema validation, permissions, filtering and pagination.
Attributes:
| Name | Type | Description |
|---|---|---|
schema |
type[BaseModel] | None
|
Pydantic model class used to validate request data and serialize responses.
Set it on the subclass or override |
queryset |
QuerySet | None
|
Tortoise QuerySet the view operates on. Set it on the subclass or
override |
filter_class |
list[type[BaseFilter]]
|
Filter classes applied in |
permission_classes |
Iterable[type[BasePermission]]
|
Permission classes checked before the handler runs. Defaults
to |
pagination_class |
type[BasePagination]
|
Pagination class used by |
search_fields |
list[str] | dict[str, str]
|
Fields matched by |
filter_fields |
list[str] | dict[str, str]
|
Fields allowed for exact filtering by |
ordering_fields |
list[str] | dict[str, str]
|
Fields allowed for ordering via |
get_schema ¶
Return the Pydantic model class for this view action.
Override this method (or set class attribute schema) like DRF's get_serializer_class /
serializer_class. Uses self.action and self.request set by as_view — do not pass
request as a parameter.
filter_queryset ¶
The filter class should be obtained first from view class or, if not, from settings
normalize_pk ¶
Coerce the route parameter pk to the model's pk type before it reaches a query.
Sanic always hands <pk> over as str. Querying with the raw str only works by implicit conversion,
and a non-integer pk against an int field raises ValueError deep inside Tortoise (a 500).
Convert up front: a pk that cannot be parsed can never match a row, so respond 404.
check_permissions
async
¶
Check view-level permissions. Permission classes are used as callables on the class (no instantiation). Supports both sync and async has_permission().
check_object_permissions
async
¶
Check object-level permissions. Permission classes are used as callables on the class (no instantiation). Supports both sync and async has_object_permission().
as_view
classmethod
¶
Construct a view function for registering with Sanic.
actions maps an HTTP method to a view method, for example `{"get": "list"}or{"get": "retrieve"}.
Callers pass this map explicitly:SanicRouter.registerbuilds it,
andadd_routecallers pass it themselves. Sanic's default route method is GET; that does not chooselistversusretrieve``.
Differences between the three composite classes:
| Class | Provided actions |
|---|---|
BaseViewSet |
create / list / retrieve / update / destroy |
ReadOnlyModelViewSet |
list / retrieve |
CreateAndReadOnlyModelViewSet |
create / list / retrieve |
BaseViewSet ¶
Bases: GenericAPIView, ModelMixin
Full-featured ViewSet: all five CRUD actions plus schema validation,
permissions, filtering and pagination from GenericAPIView.
ReadOnlyModelViewSet ¶
Bases: GenericAPIView, ListModelMixin, RetrieveModelMixin
Read-only ViewSet exposing only list and retrieve.
CreateAndReadOnlyModelViewSet ¶
Bases: GenericAPIView, CreateModelMixin, ListModelMixin, RetrieveModelMixin
ViewSet exposing create, list and retrieve — no update or delete.
CRUD mixins¶
Each mixin provides a single action; inherit from them directly when you need finer-grained composition.
CreateModelMixin ¶
Behavior of create:
- Returns
400when the request body is not JSON. - Validates input with
schemausingstrict=True, then callsperform_create(). - Serializes output with the same schema and returns
201. - Database unique constraint violations (
IntegrityError) are converted to409 TargetObjectAlreadyExist.
When looking up an object, the primary key type is normalized first, then object-level permission checks run; if the object does not exist, 404 is returned.
UpdateModelMixin ¶
perform_update() only writes fields explicitly provided in the request (exclude_unset=True) and skips primary key fields.
DestroyModelMixin ¶
Returns 204 No Content after a successful delete.
ListModelMixin ¶
The execution order of list is: get_queryset() → filter_queryset() → pagination_class.from_queryset() → paginate(). See Pagination for the response structure.
ModelMixin ¶
Bases: CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, ListModelMixin
Convenience bundle of all five CRUD mixins (create, retrieve, update, destroy, list).
Action decorator¶
action declares a regular method in a ViewSet as a standalone endpoint; SanicRouter discovers and registers it automatically.
action ¶
action(*, detail: bool = False, methods: Sequence[str] = ('GET',), url_path: str | None = None, url_name: str | None = None, **kwargs) -> Callable
Mark a method as a viewset action.
:param methods: List of HTTP methods allowed for this action :param detail: If True, action requires a pk parameter. If False, action is on collection. :param url_path: Custom URL path for this action, default to be the name of the method :param url_name: Custom URL name for this action, default to be the name of the method
validate_request is used to decorate functional views (for example, register and verify_email in srf.auth). Request validation for ViewSets is handled uniformly by as_view(), so there is no need to stack this decorator on top.
Export list¶
The following names are available from from srf.views import ...:
from srf.views import (
BaseViewSet,
CreateAndReadOnlyModelViewSet,
CreateModelMixin,
DestroyModelMixin,
GenericAPIView,
ListModelMixin,
ModelMixin,
ReadOnlyModelViewSet,
RetrieveModelMixin,
UpdateModelMixin,
action,
)
validate_request is not in the export list and must be imported from srf.views.decorators.