Skip to content

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.

from srf.views import BaseViewSet, GenericAPIView, ReadOnlyModelViewSet, action

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

GenericAPIView(*args, **kwargs)

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 get_schema().

queryset QuerySet | None

Tortoise QuerySet the view operates on. Set it on the subclass or override get_queryset().

filter_class list[type[BaseFilter]]

Filter classes applied in list(). Defaults to settings.DEFAULT_FILTERS when not declared on the class.

permission_classes Iterable[type[BasePermission]]

Permission classes checked before the handler runs. Defaults to settings.DEFAULT_PERMISSION_CLASSES.

pagination_class type[BasePagination]

Pagination class used by list(). Defaults to settings.PAGINATION_CLASS.

search_fields list[str] | dict[str, str]

Fields matched by SearchFilter via ?search= (icontains). Accepts a list of ORM field names or a dict of {alias: orm_field}.

filter_fields list[str] | dict[str, str]

Fields allowed for exact filtering by QueryParamFilter / JsonLogicFilter. Accepts a list or a dict of {param: orm_field}.

ordering_fields list[str] | dict[str, str]

Fields allowed for ordering via ?ordering=. Use -name for descending order.

get_schema
get_schema() -> type[BaseModel]

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.

get_queryset
get_queryset() -> QuerySetType

Prioritize using get_queryset, followed by queryset

filter_queryset
filter_queryset(queryset)

The filter class should be obtained first from view class or, if not, from settings

get_object async
get_object(pk)

Get an orm model instance.

normalize_pk
normalize_pk(pk, model: type[Model] | None = None)

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_permissions(request: Request)

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_permissions(obj: Model)

Check object-level permissions. Permission classes are used as callables on the class (no instantiation). Supports both sync and async has_object_permission().

get_current_user
get_current_user(request: Request)

Retrieve the currently logged-in user

as_view classmethod
as_view(actions: dict[str, str] | None = None)

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

BaseViewSet(*args, **kwargs)

Bases: GenericAPIView, ModelMixin

Full-featured ViewSet: all five CRUD actions plus schema validation, permissions, filtering and pagination from GenericAPIView.

ReadOnlyModelViewSet

ReadOnlyModelViewSet(*args, **kwargs)

Bases: GenericAPIView, ListModelMixin, RetrieveModelMixin

Read-only ViewSet exposing only list and retrieve.

CreateAndReadOnlyModelViewSet

CreateAndReadOnlyModelViewSet(*args, **kwargs)

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

create async
create(request: Request, *args, **kwargs) -> HTTPResponse

Create an orm model instance.

perform_create async
perform_create(sch_model: BaseModel) -> TorModel

sch_model: instance of BaseModel

Behavior of create:

  • Returns 400 when the request body is not JSON.
  • Validates input with schema using strict=True, then calls perform_create().
  • Serializes output with the same schema and returns 201.
  • Database unique constraint violations (IntegrityError) are converted to 409 TargetObjectAlreadyExist.

RetrieveModelMixin

retrieve async
retrieve(request: Request, pk, *args, **kwargs) -> JSONResponse

Get an orm model instance.

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

update async
update(request: Request, pk, *args, **kwargs) -> JSONResponse

Update an orm model instance.

perform_update async
perform_update(sch_model: BaseModel, orm_model: Model) -> TorModel

sch_model: instance of BaseModel orm_model: instance of TorModel

perform_update() only writes fields explicitly provided in the request (exclude_unset=True) and skips primary key fields.

DestroyModelMixin

destroy async
destroy(request: Request, pk, *args, **kwargs) -> HTTPResponse

Delete an orm model instance.

perform_destroy async
perform_destroy(orm_model: Model) -> None

orm_model: instance of TorModel

Returns 204 No Content after a successful delete.

ListModelMixin

list async
list(request: Request, *args, **kwargs) -> JSONResponse

Get a list orm model instance.

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.

validate_request

validate_request(show_errors: bool = False)

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.