Using controllers#

Controller#

class dmr.controller.Controller(**kwargs)[source]#

Bases: View, Generic[_SerializerT_co]

Defines API views as controllers.

Controller is a django.views.generic.base.View subclass that should be used as a base for all REST endpoints.

endpoint_cls#

Class to create endpoints with.

Type:

ClassVar[type[dmr.endpoint.Endpoint]]

serializer#

Serializer that is passed via type parameters. The main goal of the serializer is to serialize object to json and deserialize them from json. You can’t change the serializer simply by modifying the attribute in the controller class. Because it is already passed to many other places. To customize it: create a new class, subclass BaseSerializer, and pass the new type as a type argument to the controller.

Type:

ClassVar[type[dmr.serializer.BaseSerializer]]

settings_validator_cls#

Runs settings validation once the first controller is created.

Type:

ClassVar[type[dmr.validation.settings.SettingsValidator]]

no_validate_http_spec#

Set of http spec validation checks that we disable for this class. Overrides the settings value, can be overridden per endpoint. Set it to None to enable all checks back.

Type:

ClassVar[collections.abc.Set[dmr.settings.HttpSpec] | EMPTY | None]

validate_responses#

Boolean whether or not validating responses. Works in runtime, can be disabled for better performance.

Type:

ClassVar[bool | EMPTY]

exclude_validate_responses#

Set of status codes that we don’t validate, even when validate_responses is enabled. Useful for errors like 500 that can be raised from anywhere and that you might not want to describe. Overrides the settings value, can be overridden per endpoint. Set it to None to validate all status codes back.

Type:

ClassVar[collections.abc.Set[http.HTTPStatus] | EMPTY | None]

semantic_schema#

Should we generate any semantic schema for endpoints in this controller?

Type:

ClassVar[bool | EMPTY]

semantic_responses#

Should semantic responses be collected from different providers for all endpoints in this class.

Type:

ClassVar[bool | EMPTY]

exclude_semantic_responses#

Set of semantic responses that user wants to disable. Overrides the settings value, can be overridden per endpoint. Set it to None to enable all semantic responses back.

Type:

ClassVar[collections.abc.Set[http.HTTPStatus] | EMPTY | None]

semantic_auth#

Should semantic auth be collected from different providers for this endpoint. Overrides settings value.

Type:

bool | EMPTY

exclude_semantic_auth#

Set of semantic security requirements names that should not be collected. Overrides settings value.

Type:

collections.abc.Set[str] | EMPTY | None

responses#

List of responses schemas that this controller can return. Overrides 'responses' key in the settings, can be overridden per endpoint. Set it to None to not use any responses from the settings.

Type:

ClassVar[collections.abc.Sequence[dmr.metadata.ResponseSpec] | EMPTY | None]

allowed_http_methods#

Set of names to be treated as names for endpoints. Does not include options, but includes meta.

Type:

ClassVar[collections.abc.Set[str]]

parsers#

Sequence of parsers to be used for this controller to parse incoming request’s body. All instances must be of subtypes of Parser. Overrides the settings value, can be overridden per endpoint.

Type:

ClassVar[collections.abc.Sequence[dmr.parsers.Parser] | EMPTY]

renderers#

Sequence of renderers to be used for this controller to render response’s body. All instances must be of subtypes of Renderer. Overrides the settings value, can be overridden per endpoint.

Type:

ClassVar[collections.abc.Sequence[dmr.renderers.Renderer] | EMPTY]

validate_negotiation#

Should we validate that returned response’s Content-Type header matches the one that we inferred in the negotiation process?

Type:

ClassVar[bool | EMPTY]

auth#

Sequence of auth instances to be used for this controller. Sync controllers must use instances of dmr.security.SyncAuth. Async controllers must use instances of dmr.security.AsyncAuth. Overrides the settings value, can be overridden per endpoint. Set it to None to disable auth of this controller.

Type:

ClassVar[collections.abc.Sequence[dmr.security.base.SyncAuth] | collections.abc.Sequence[dmr.security.base.AsyncAuth] | EMPTY | None]

throttling#

Sequence of throttle instances to be used. Sync controllers must use instances of dmr.throttling.SyncThrottle. Async controllers must use instances of dmr.throttling.AsyncThrottle. Overrides the settings value, can be overridden per endpoint. Set it to None to disable throttling of this controller.

Type:

ClassVar[collections.abc.Sequence[dmr.throttling.base.SyncThrottle] | collections.abc.Sequence[dmr.throttling.base.AsyncThrottle] | EMPTY | None]

error_model#

Schema type that represents and validates common error responses.

Type:

ClassVar[typing_extensions.TypeForm[Any]]

is_abstract#

Whether or not this controller is abstract. We consider controller “abstract” when it does not have exact serializer type or exact api_endpoints instances. You can also set it to True explicitly to make a controller with an exact serializer reusable without routing it: it does not build any endpoints, only its subclasses do. Subclasses that don’t declare is_abstract themselves become concrete again. Abstract controllers cannot be routed, as_view raises EndpointMetadataError for them.

Type:

ClassVar[bool]

is_async#

Whether or not this controller is async.

Type:

ClassVar[bool | None]

streaming#

Does this controller work with streaming responses like SSE?

Type:

ClassVar[bool]

extras#

Default extras instance for this controller. Setting it enables extras= in @modify and @validate for all endpoints and provides controller-level defaults. EMPTY means that extras are not supported. See Providing extras for @modify and @validate to learn more.

Type:

ClassVar[dmr.internal.endpoint.Extras[Any] | EMPTY]

controller_validator_cls#

Runs full controller validation on definition.

Type:

ClassVar[type[dmr.validation.controller.ControllerValidator]]

annotations_context#

Inference context to call typing.get_type_hints() for this controller.

Type:

ClassVar[dmr.types.AnnotationsContext]

api_endpoints#

Dictionary of HTTPMethod name to controller instance.

Type:

ClassVar[collections.abc.Mapping[str, dmr.endpoint.Endpoint]]

csrf_exempt#

Should this controller be exempted from the CSRF check? Is True by default. See CSRF to configure the CSRF correctly to support REST responses. It is only supported on the controller level, because it has its own per-method logic inside Django’s original CSRF middleware.

Type:

ClassVar[bool]

login_required#

Whether this controller should be handled by Django’s LoginRequiredMiddleware. Is False by default. Users should make use of authentication in django-modern-rest. See How authentication works for more details.

Type:

ClassVar[bool]

summary#

A short summary of what this path item does. Defaults to the first paragraph of the controller’s docstring. Set it to None to have no summary at all.

Type:

ClassVar[str | django.utils.functional.Promise | EMPTY | None]

description#

A verbose explanation of the path item behavior. Defaults to everything that goes after the first paragraph of the controller’s docstring. Set it to None to have no description at all.

Type:

ClassVar[str | django.utils.functional.Promise | EMPTY | None]

tags#

A list of tags to group all operations from this controller in OpenAPI documentation. Overrides router-level tags, can be overridden per endpoint. Set it to None to have no tags at all.

Type:

ClassVar[collections.abc.Sequence[str] | EMPTY | None]

security#

A sequence of security requirement objects for all operations in this controller. Overrides security of dmr.openapi.OpenAPIConfig, can be overridden per endpoint. Set it to None to disable security for this controller. It is merged with the requirements generated from auth, but it never affects the runtime auth. Useful to document external security mechanisms, for example, the ones enforced by an HTTP proxy. Used security schemes must be declared as security_schemes in components of dmr.openapi.OpenAPIConfig. See Customizing security.

Type:

ClassVar[collections.abc.Sequence[dict[str, list[str]]] | EMPTY | None]

servers#

An alternative servers array to service all operations in this controller. Can be overridden per endpoint. Set it to None to have no servers at all.

Type:

ClassVar[collections.abc.Sequence[dmr.openapi.objects.server.Server] | EMPTY | None]

deprecated#

Declares all operations in this controller to be deprecated. Overrides router-level value, can be overridden per endpoint.

Type:

ClassVar[bool | EMPTY]

external_docs#

Additional external documentation for all operations in this controller. Can be overridden per endpoint. Set it to None to have no external docs at all.

Type:

ClassVar[dmr.openapi.objects.external_documentation.ExternalDocumentation | EMPTY | None]

callbacks#

A map of possible out-of band callbacks related to all operations in this controller. Can be overridden per endpoint. Set it to None to have no callbacks at all.

Type:

ClassVar[collections.abc.Mapping[str, dict[str, dmr.openapi.objects.path_item.PathItem | dmr.openapi.objects.reference.Reference] | dmr.openapi.objects.reference.Reference] | EMPTY | None]

x_extensions#

Specification extensions of the PathItem of this controller, keys must start with x-. Unlike other OpenAPI attributes, it is not a default for the operations: every OpenAPI object has its own extensions, so nothing is inherited or merged. Use x_extensions of modify() or validate() for an operation.

Type:

ClassVar[collections.abc.Mapping[str, Any] | None]

ignore_from_spec#

If set to True, all endpoints from this controller would not be added to the final OpenAPI spec.

Type:

ClassVar[bool]

request#

Current HttpRequest instance.

args#

Path positional parameters of the request.

kwargs#

Path named parameters of the request.

Type:

dict[str, Any]

Changed in version 0.16.0: Explicit is_abstract definitions are now respected: abstract controllers do not build any endpoints. Added deprecated, external_docs, callbacks, and x_extensions. servers is now resolved per endpoint and dumped on operations, not on the path item.

classmethod __init_subclass__() → None[source]#

Construct a controller.

classmethod as_view(**initkwargs: Any) → Callable[[...], HttpResponseBase][source]#

Returns a view function for the class-based view.

This override applies CSRF exemption to the view. Session-based authentication will still be explicitly validated for CSRF, while all other authentication methods will be CSRF-exempt.

This override also applies whether a login is required or not. By default, login is not required to exempt the view from Django’s LoginRequiredMiddleware. Users should make use of authentication in django-modern-rest. See How authentication works for more details.

Changing class-level attributes, like throttling, with initkwargs is not supported. But they are not rejected: all initkwargs are passed to the next as_view in the MRO as is, so other base classes can accept their own keyword arguments, see Arguments of as_view.

Raises:

EndpointMetadataError – When called on an abstract controller, because it has nothing to serve.

Changed in version 0.16.0: Abstract controllers now raise EndpointMetadataError instead of silently returning a broken view.

Controllers now set login_required to False by default in order to exempt controllers from Django’s LoginRequiredMiddleware.

dispatch(request: HttpRequest, *args: Any, **kwargs: Any) → HttpResponseBase[source]#

Find an endpoint that serves this HTTP method and call it.

Return 405 if this method is not allowed.

format_error(error: str | Exception, *, loc: str | list[str | int] | None = None, error_type: str | ErrorType | None = None) → Any[source]#

Convert error to the common format.

Parameters:
  • error – A serialization exception like a validation error.

  • loc – Location where this error happened. Like "headers", or "field_name", or ["parsed_headers", "header_name"].

  • error_type – Optional type of the error for extra metadata.

Returns:

Simple python object - exception converted to a common format.

classmethod get_schema(route_metadata: InternalRouteMetadata, context: OpenAPIContext, router: Router) → PathItem | None[source]#

Generate OpenAPI spec for path items.

Changed in version 0.13.0:

  • Renamed from get_path_item to get_schema

  • Now allows to return None to ignore whole path items from OpenAPI schema

Changed in version 0.16.0: summary and description are now parsed from the controller’s docstring when they are not set explicitly. Changed path and pattern parameters to be route_metadata instead. servers is not set on the path item anymore, it is resolved per endpoint instead.

async handle_async_error(endpoint: Endpoint, controller: Controller[_SerializerT_co], exc: Exception) → HttpResponse[source]#

Return error response if possible. Async case.

Override this method to add custom error handling for async execution. By default - does nothing, only re-raises the passed error. Won’t be called when using sync endpoints.

handle_error(endpoint: Endpoint, controller: Controller[_SerializerT_co], exc: Exception) → HttpResponse[source]#

Return error response if possible. Sync case.

Override this method to add custom error handling for sync execution. By default - does nothing, only re-raises the passed error. Won’t be called when using async endpoints.

handle_method_not_allowed(method: str) → HttpResponse[source]#

Return error response for 405 response code.

It is special in way that we don’t have an endpoint associated with it.

http_method_not_allowed(request: HttpRequest, *args: Any, **kwargs: Any) → HttpResponse[source]#

Do not use, use handle_method_not_allowed() instead.

View.http_method_not_allowed raises an error in a wrong format.

options(request: HttpRequest, *args: Any, **kwargs: Any) → HttpResponse[source]#

Do not use, define your own meta method instead.

Django’s View.options has incompatible signature with django-modern-rest. It would be a typing error to define something like:

Warning

Don’t do this!

>>> from http import HTTPStatus
>>> from dmr import Controller, validate
>>> from dmr.plugins.pydantic import (
...     PydanticSerializer,
... )
>>> class MyController(Controller[PydanticSerializer]):
...     @validate(
...         ResponseSpec(
...             None,
...             status_code=HTTPStatus.NO_CONTENT,
...         ),
...     )
...     def options(self) -> HttpResponse:  # <- typing problem
...         ...

That’s why instead of options you should define our own meta method:

>>> class MyController(Controller[PydanticSerializer]):
...     @validate(
...         ResponseSpec(
...             None,
...             status_code=HTTPStatus.NO_CONTENT,
...         ),
...     )
...     def meta(self) -> HttpResponse:
...         allow = ','.join(
...             method.upper()
...             for method in self.allowed_http_methods
...         )
...         return self.to_response(
...             None,
...             status_code=HTTPStatus.NO_CONTENT,
...             headers={'Allow': allow},
...         )

Note

By default meta method is not provided for you. If you want to support OPTIONS http method with the default implementation, use:

>>> from dmr.options_mixins import MetaMixin

>>> class ControllerWithMeta(
...     MetaMixin,
...     Controller[PydanticSerializer],
... ): ...
setup(request: HttpRequest, *args: Any, **kwargs: Any) → None[source]#

Set request context.

Unlike setup() does not set head method automatically.

Thread safety: there’s only one controller instance per request.

to_error(raw_data: Any, *, status_code: HTTPStatus, headers: Mapping[str, str] | None = None, cookies: Mapping[str, NewCookie] | None = None, renderer: Renderer | None = None) → HttpResponse[source]#

Helpful method to convert API error parts into an actual error.

Always requires the error code to be passed. Is an alias for to_response method with a siglightly different signature and semantics.

Should be always used instead of using raw django.http.HttpResponse objects. Does the usual validation, no “second validation” problem exists.

to_response(raw_data: Any, *, status_code: HTTPStatus | None = None, headers: Mapping[str, str] | None = None, cookies: Mapping[str, NewCookie] | None = None, renderer: Renderer | None = None) → HttpResponse[source]#

Helpful method to convert response parts into an actual response.

Should be always used instead of using raw django.http.HttpResponse objects. Has better serialization speed and semantics than manual. Does the usual validation, no “second validation” problem exists.

Endpoint#

class dmr.endpoint.Endpoint(func: Callable[[...], Any], *, controller_cls: type[Controller[BaseSerializer]])[source]#

Represents the single API endpoint.

Is built during the import time. In the runtime only does response validate, which can be disabled.

Changed in version 0.16.0: Endpoint no longer creates HttpResponseBase objects from modifications, now ResponseValidator returns full responses. func is now public, but __call__ is removed.

get_schema(route_metadata: InternalRouteMetadata, controller_cls: type[Controller[BaseSerializer]], context: OpenAPIContext, router: Router) → Operation[source]#

Build an OpenAPI Operation from an endpoint.

Changed in version 0.16.0: Now accepts controller_cls parameter instead of controller_name and serializer. Changed path and pattern parameters to be route_metadata.

async handle_async_error(controller: Controller[BaseSerializer], exc: Exception) → HttpResponse[source]#

Return error response if possible.

Override this method to change the endpoint error handling logic.

Changed in version 0.16.0: Now you can raise different errors from layers above. Which would be handled by lower layers.

handle_error(controller: Controller[BaseSerializer], exc: Exception) → HttpResponseBase[source]#

Return error response if possible.

Override this method to change the endpoint error handling logic.

Changed in version 0.16.0: Now you can raise different errors from layers above. Which would be handled by lower layers.

metadata_builder_cls#

alias of EndpointMetadataBuilder

metadata_cls#

alias of EndpointMetadata

metadata_merger_cls#

alias of MetadataMerger

metadata_validator_cls#

alias of EndpointMetadataValidator

payload_builder_cls#

alias of PayloadBuilder

request_negotiator_cls#

alias of RequestNegotiator

response_modification_cls#

alias of ResponseModification

response_negotiator_cls#

alias of ResponseNegotiator

response_validator_cls#

alias of ResponseValidator

serializer_context_cls#

alias of SerializerContext

validate_response(controller: Controller[BaseSerializer], response: HttpResponseBase) → HttpResponseBase[source]#

Validate a response that was created outside of this endpoint.

For example, by a middleware from wrap_middleware(). Responses of the endpoint itself are already validated.

Returns the same response when it is valid, or an error response when it is not, just like the endpoint does for its own responses.

Added in version 0.17.0.

class dmr.metadata.EndpointMetadata(*, endpoint_name: str, type_annotations: dict[str, Any], responses: dict[HTTPStatus, ResponseSpec], validate_responses: bool, method: str, modification: ResponseModification | None, error_handler: SyncErrorHandler | AsyncErrorHandler | None, component_parsers: list[ComponentParserSpec], parsers: dict[str, Parser], renderers: dict[str, Renderer], validate_negotiation: bool, auth: list[_AuthT] | None, throttling_before_auth: list[_ThrottlingT] | None, throttling_after_auth: list[_ThrottlingT] | None, exclude_validate_responses: frozenset[HTTPStatus], no_validate_http_spec: frozenset[HttpSpec], allowed_http_methods: frozenset[str], semantic_schema: bool, semantic_responses: bool, exclude_semantic_responses: frozenset[HTTPStatus], semantic_auth: bool, exclude_semantic_auth: frozenset[str], summary: str | Promise | None, description: str | Promise | None, tags: list[str] | EMPTY | None, operation_id: str | None, deprecated: bool | EMPTY, security: list[SecurityRequirement] | None, external_docs: ExternalDocumentation | None, callbacks: dict[str, Callback | Reference] | None, servers: list[Server] | None, x_extensions: dict[str, Any] | None, ignore_from_spec: bool, extras: _ExtrasT)[source]#

Base class for common endpoint metadata.

endpoint_name#

Text representation of an endpoint name for better error messages.

Type:

str

type_annotations#

Unmodified unnotations of the endpoint function, returned by the resolution method.

Type:

dict[str, Any]

responses#

Mapping of HTTP method to response description. All possible responses that this API can return. Used for OpenAPI spec generation and for response validation.

Type:

dict[http.HTTPStatus, dmr.metadata.ResponseSpec]

method#

String name of an HTTP method for this endpoint.

Type:

str

validate_responses#

Do we have to run runtime validation of responses for this endpoint? Already resolved from the global setting, the controller, and the endpoint.

Type:

bool

modification#

Default modifications that are applied to the returned data. Can be None, when @validate is used.

Type:

dmr.metadata.ResponseModification | None

error_handler#

Callback function to be called when this endpoint faces an exception.

Type:

SyncErrorHandler | AsyncErrorHandler | None

component_parsers#

List of component parser specifications from the controller. Each spec is a named tuple of (ComponentParser instance, model, model meta, default).

Type:

list[ComponentParserSpec]

parsers#

List of instances to be used for this endpoint to parse incoming request’s body. All instances must be of subtypes of Parser.

Type:

dict[str, Parser]

renderers#

List of instances to be used for this endpoint to render response’s body. All instances must be of subtypes of Renderer.

Type:

dict[str, Renderer]

validate_negotiation#

Should we validate that returned response’s Content-Type header matches the one that we inferred in the negotiation process?

Type:

bool

auth#

list of auth instances to be used for this endpoint. Sync endpoints must use instances of dmr.security.SyncAuth. Async endpoints must use instances of dmr.security.AsyncAuth. When set it to None it means that auth is disabled for this endpoint.

Type:

list[dmr.metadata._AuthT] | None

throttling#

Sequence of throttle instances to be used for this endpoint. Sync endpoints must use instances of dmr.throttling.SyncThrottle. Async endpoints must use instances of dmr.throttling.AsyncThrottle. Set it to None to disable throttling of this endpoint.

Type:

list[dmr.metadata._ThrottlingT] | None

throttling_before_auth#

Sequence of throttle instances to be used before auth checks.

Type:

list[dmr.metadata._ThrottlingT] | None

throttling_after_auth#

Sequence of throttle instances to be used after auth checks.

Type:

list[dmr.metadata._ThrottlingT] | None

exclude_validate_responses#

Set of status codes that we don’t validate, even when validate_responses is enabled.

Type:

frozenset[http.HTTPStatus]

no_validate_http_spec#

Set of checks that user wants to disable for validation in this endpoint.

Type:

frozenset[HttpSpec]

allowed_http_methods#

Set of extra HTTP methods that are allowed for this endpoint.

Type:

frozenset[str]

semantic_responses#

Should semantic responses from different providers be collected?

Type:

bool

exclude_semantic_responses#

Set of semantic responses that user wants to disable.

Type:

frozenset[http.HTTPStatus]

summary#

A short summary of what the operation does.

Type:

str | django.utils.functional.Promise | None

description#

A verbose explanation of the operation behavior.

Type:

str | django.utils.functional.Promise | None

tags#

A list of tags for API documentation control. Used to group operations in OpenAPI documentation. Already resolved from the endpoint and the controller, EMPTY means that router-level tags are used during the schema generation.

Type:

list[str] | EMPTY | None

operation_id#

Unique string used to identify the operation.

Type:

str | None

deprecated#

Declares this operation to be deprecated. Already resolved from the endpoint and the controller, EMPTY means that the router-level value is used during the schema generation.

Type:

bool | EMPTY

security#

A declaration of which security mechanisms can be used for this operation. List of security requirement objects. Already resolved from the endpoint, the controller, and security of OpenAPIConfig from the settings: the first explicitly defined level wins. They are merged with the requirements from auth during the schema generation. When set to None it means that no user provided security is used for this endpoint.

Type:

list[SecurityRequirement] | None

external_docs#

Additional external documentation for this operation. Already resolved from the endpoint and the controller.

Type:

ExternalDocumentation | None

callbacks#

A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. Already resolved from the endpoint and the controller.

Type:

dict[str, Callback | Reference] | None

servers#

An alternative servers array to service this operation. If a servers array is specified at the OpenAPI Object level, it will be overridden by this value. Already resolved from the endpoint and the controller.

Type:

list[Server] | None

x_extensions#

Specification extensions of this operation, keys must start with x-. Endpoint-only field, it is never resolved from the controller: Controller.x_extensions describes the path item.

Type:

dict[str, Any] | None

ignore_from_spec#

If set to True, this endpoint would not be added to the final OpenAPI spec.

Type:

bool

extras#

Extra settings for custom controllers, built by build() of extras. It is None when the controller does not support extras. See Providing extras for @modify and @validate to learn more.

Type:

dmr.metadata._ExtrasT

method can be a custom name, not specified in http.HTTPMethod enum, when allowed_http_methods is used for endpoint definition. This might be useful for cases like when you need to define a method like query, which is not yet formally accepted. Or provide domain specific HTTP methods.

Changed in version 0.16.0: It is now a generic class. extras is added.

__post_init__() → None[source]#

Set pre-computed fields.

collect_response_specs(controller_cls: type[Controller[BaseSerializer]], existing_responses: dict[HTTPStatus, ResponseSpec]) → list[ResponseSpec][source]#

Collect unique responses for all possible response providers.

response_spec_providers() → list[ResponseSpecProvider][source]#

Determine: from where we should collect response schemas.

Override this method in your own metadata classes if you want more or less response spec providers.

For example: you can add some custom field to Controller like checks=. And you can subclass EndpointMetadata to also contain checks field and override this method to also include response specs from this field.

Define semantic_responses to False on settings or controller level to disable semantic responses collection.

dmr.endpoint.request_endpoint(request: HttpRequest, *, strict: Literal[True]) → Endpoint[source]#
dmr.endpoint.request_endpoint(request: HttpRequest, *, strict: bool = False) → Endpoint | None

Return an instance of the Endpoint that was used for this request.

When strict is passed and request has no endpoint, we raise AttributeError. This can happen for 405 responses, for example. They don’t have endpoints. All others do.

Added in version 0.7.0.

Modify#

final class dmr.endpoint.ModifyEndpoint(extras_cls: type[_ExtrasT] | EMPTY = EMPTY)[source]#

Decorator to modify endpoints that return raw model data.

Apply it to change some API parts:

>>> from http import HTTPStatus
>>> from dmr import Controller, modify
>>> from dmr.plugins.pydantic import PydanticFastSerializer

>>> class TaskController(Controller[PydanticFastSerializer]):
...     @modify(status_code=HTTPStatus.ACCEPTED)
...     def post(self) -> list[int]:
...         return [1, 2]  # id of tasks you have started
Parameters:
  • status_code – Shows status_code in the documentation. When status_code is passed, always use it by default. When not provided, we use smart inference based on the HTTP method name for default returned response.

  • headers – Shows headers in the documentation. When headers are passed we will add them for the default response.

  • cookies – Shows cookies in the documentation. When cookies are passed we will add them for the default response.

  • validate_responses – Do we have to run runtime validation of responses for this endpoint? Customizable via global setting, per controller, and per endpoint. Here we only store the per endpoint information.

  • exclude_validate_responses – Set of status codes that we don’t validate, even when validate_responses is enabled. Useful for errors like 500 that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it to None to validate all status codes back.

  • semantic_schema – Should we generate any semantic schema for this endpoint?

  • semantic_responses – Should semantic responses be collected from different providers for this endpoint.

  • exclude_semantic_responses – Set of semantic responses status codes that user wants to disable. Overrides controller and settings values. Set it to None to enable all semantic responses back.

  • semantic_auth – Should semantic auth be collected from different providers for this endpoint. Overrides controller and settings values.

  • exclude_semantic_auth – Set of semantic security requirements names that should not be collected. Overrides controller and settings values.

  • extra_responses – Sequence of extra responses that this endpoint can return. Overrides controller and settings values. Set it to None to only use the default response.

  • no_validate_http_spec – Set of http spec validation checks that we disable for this endpoint. Overrides controller and settings values. Set it to None to enable all checks back.

  • error_handler – Callback function to be called when this endpoint faces an exception.

  • parsers – Sequence of types to be used for this endpoint to parse incoming request’s body. All types must be subtypes of Parser. Overrides controller and settings values.

  • renderers – Sequence of types to be used for this endpoint to render response’s body. All types must be subtypes of Renderer. Overrides controller and settings values.

  • validate_negotiation – Should we validate that returned response’s Content-Type header matches the one that we inferred in the negotiation process?

  • auth – Sequence of auth instances to be used for this endpoint. Sync endpoints must use instances of dmr.security.SyncAuth. Async endpoints must use instances of dmr.security.AsyncAuth. Overrides controller and settings values. Set it to None to disable auth for this endpoint.

  • throttling – Sequence of throttle instances to be used for this endpoint. Sync endpoints must use instances of dmr.throttling.SyncThrottle. Async endpoints must use instances of dmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it to None to disable throttling of this endpoint.

  • summary – A short summary of what the operation does. Defaults to the first paragraph of the endpoint’s docstring. Set it to None to have no summary at all.

  • description – A verbose explanation of the operation behavior. Defaults to everything that goes after the first paragraph of the endpoint’s docstring. Set it to None to have no description at all.

  • tags – A sequence of tags for API documentation control. Used to group operations in OpenAPI documentation. Overrides controller-level and router-level tags. Set it to None to have no tags at all.

  • operation_id – Unique string used to identify the operation.

  • deprecated – Declares this operation to be deprecated. Overrides controller-level and router-level values. Set it to False to explicitly mark this operation as not deprecated, even if its controller or router is.

  • security – A sequence of security requirement objects for this operation. Overrides the controller value and security of dmr.openapi.OpenAPIConfig. Set it to None to disable security of this endpoint. It is merged with the requirements generated from auth, but it never affects the runtime auth. Useful to document external security mechanisms, for example, the ones enforced by an HTTP proxy. Used security schemes must be declared as security_schemes in components of dmr.openapi.OpenAPIConfig. See Customizing security.

  • external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to None to have no external docs at all.

  • callbacks – A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. Overrides the controller value. Set it to None to have no callbacks at all.

  • servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to None to have no servers at all.

  • x_extensions – Specification extensions of this operation, keys must start with x-. Set only on this operation: it is never inherited from or merged with x_extensions, which describes the path item, not its operations.

  • links – Possible links to other OpenAPI operations.

  • response_description – Description for the generated response object.

  • ignore_from_spec – If set to True, this endpoint would not be added to the final OpenAPI spec.

  • extras – Extra settings for custom controllers. See Providing extras for @modify and @validate to learn more.

Returns:

The same function with __dmr_payload__ payload instance.

Warning

Do not disable validate_responses unless this is performance critical for you!

Changed in version 0.15.0: modify used to be a function, now it is an instance with lazy method for lazy reusable endpoints.

Changed in version 0.16.0: Removed validate_events parameter, added extras parameter instead. This class is now generic and public.

__call__(*, error_handler: EMPTY = EMPTY, status_code: HTTPStatus | EMPTY = EMPTY, headers: Mapping[str, NewHeader | HeaderSpec] | EMPTY = EMPTY, cookies: Mapping[str, NewCookie | CookieSpec] | EMPTY = EMPTY, validate_responses: bool | EMPTY = EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_schema: bool | EMPTY = EMPTY, semantic_responses: bool | EMPTY = EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_auth: bool | EMPTY = EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None = EMPTY, extra_responses: Sequence[ResponseSpec] | EMPTY | None = EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None = EMPTY, parsers: Sequence[Parser] | EMPTY = EMPTY, renderers: Sequence[Renderer] | EMPTY = EMPTY, validate_negotiation: bool | EMPTY = EMPTY, auth: Sequence[Never] | EMPTY | None = EMPTY, throttling: Sequence[Never] | EMPTY | None = EMPTY, summary: str | Promise | EMPTY | None = EMPTY, description: str | Promise | EMPTY | None = EMPTY, tags: Sequence[str] | EMPTY | None = EMPTY, operation_id: str | EMPTY = EMPTY, deprecated: bool | EMPTY = EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None = EMPTY, external_docs: ExternalDocumentation | EMPTY | None = EMPTY, callbacks: Mapping[str, Callback | Reference] | EMPTY | None = EMPTY, servers: Sequence[Server] | EMPTY | None = EMPTY, x_extensions: Mapping[str, Any] | EMPTY = EMPTY, links: Mapping[str, Link | Reference] | EMPTY = EMPTY, response_description: str | EMPTY = EMPTY, ignore_from_spec: bool | EMPTY = EMPTY, extras: _ExtrasT | EMPTY = EMPTY) → ModifyAnyCallable[source]#
__call__(*, error_handler: AsyncErrorHandler | EMPTY = EMPTY, status_code: HTTPStatus | EMPTY = EMPTY, headers: Mapping[str, NewHeader | HeaderSpec] | EMPTY = EMPTY, cookies: Mapping[str, NewCookie | CookieSpec] | EMPTY = EMPTY, validate_responses: bool | EMPTY = EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_schema: bool | EMPTY = EMPTY, semantic_responses: bool | EMPTY = EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_auth: bool | EMPTY = EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None = EMPTY, extra_responses: Sequence[ResponseSpec] | EMPTY | None = EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None = EMPTY, parsers: Sequence[Parser] | EMPTY = EMPTY, renderers: Sequence[Renderer] | EMPTY = EMPTY, validate_negotiation: bool | EMPTY = EMPTY, auth: Sequence[AsyncAuth] | EMPTY | None = EMPTY, throttling: Sequence[AsyncThrottle] | EMPTY | None = EMPTY, summary: str | Promise | EMPTY | None = EMPTY, description: str | Promise | EMPTY | None = EMPTY, tags: Sequence[str] | EMPTY | None = EMPTY, operation_id: str | EMPTY = EMPTY, deprecated: bool | EMPTY = EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None = EMPTY, external_docs: ExternalDocumentation | EMPTY | None = EMPTY, callbacks: Mapping[str, Callback | Reference] | EMPTY | None = EMPTY, servers: Sequence[Server] | EMPTY | None = EMPTY, x_extensions: Mapping[str, Any] | EMPTY = EMPTY, links: Mapping[str, Link | Reference] | EMPTY = EMPTY, response_description: str | EMPTY = EMPTY, ignore_from_spec: bool | EMPTY = EMPTY, extras: _ExtrasT | EMPTY = EMPTY) → ModifyAsyncCallable
__call__(*, error_handler: SyncErrorHandler | EMPTY = EMPTY, status_code: HTTPStatus | EMPTY = EMPTY, headers: Mapping[str, NewHeader | HeaderSpec] | EMPTY = EMPTY, cookies: Mapping[str, NewCookie | CookieSpec] | EMPTY = EMPTY, validate_responses: bool | EMPTY = EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_schema: bool | EMPTY = EMPTY, semantic_responses: bool | EMPTY = EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_auth: bool | EMPTY = EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None = EMPTY, extra_responses: Sequence[ResponseSpec] | EMPTY | None = EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None = EMPTY, parsers: Sequence[Parser] | EMPTY = EMPTY, renderers: Sequence[Renderer] | EMPTY = EMPTY, validate_negotiation: bool | EMPTY = EMPTY, auth: Sequence[SyncAuth] | EMPTY | None = EMPTY, throttling: Sequence[SyncThrottle] | EMPTY | None = EMPTY, summary: str | Promise | EMPTY | None = EMPTY, description: str | Promise | EMPTY | None = EMPTY, tags: Sequence[str] | EMPTY | None = EMPTY, operation_id: str | EMPTY = EMPTY, deprecated: bool | EMPTY = EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None = EMPTY, external_docs: ExternalDocumentation | EMPTY | None = EMPTY, callbacks: Mapping[str, Callback | Reference] | EMPTY | None = EMPTY, servers: Sequence[Server] | EMPTY | None = EMPTY, x_extensions: Mapping[str, Any] | EMPTY = EMPTY, links: Mapping[str, Link | Reference] | EMPTY = EMPTY, response_description: str | EMPTY = EMPTY, ignore_from_spec: bool | EMPTY = EMPTY, extras: _ExtrasT | EMPTY = EMPTY) → ModifySyncCallable

Adds the payload to the endpoint function.

extras_cls: type[_ExtrasT] | EMPTY#

Extras class that this decorator instance supports.

Pass it to create a typed decorator: ModifyEndpoint(MyExtras). Controllers using such decorator must use the same extras class in extras.

lazy(provider: _CallableOrClassmethod[_ControllerT, _ModifyDecoratorT]) → _ModifyDecoratorT[source]#

Create lazy endpoint for reusable controller definition.

This provides an agile way to customize all the response details, including headers and cookies spec, response status code, OpenAPI metadata and other things.

See Lazy reusable endpoints for the full example.

Added in version 0.15.0.

dmr.endpoint.modify = ModifyEndpoint(extras_cls=EMPTY)#

Decorator to modify endpoints that return raw model data.

Apply it to change some API parts:

>>> from http import HTTPStatus
>>> from dmr import Controller, modify
>>> from dmr.plugins.pydantic import PydanticFastSerializer

>>> class TaskController(Controller[PydanticFastSerializer]):
...     @modify(status_code=HTTPStatus.ACCEPTED)
...     def post(self) -> list[int]:
...         return [1, 2]  # id of tasks you have started
Parameters:
  • status_code – Shows status_code in the documentation. When status_code is passed, always use it by default. When not provided, we use smart inference based on the HTTP method name for default returned response.

  • headers – Shows headers in the documentation. When headers are passed we will add them for the default response.

  • cookies – Shows cookies in the documentation. When cookies are passed we will add them for the default response.

  • validate_responses – Do we have to run runtime validation of responses for this endpoint? Customizable via global setting, per controller, and per endpoint. Here we only store the per endpoint information.

  • exclude_validate_responses – Set of status codes that we don’t validate, even when validate_responses is enabled. Useful for errors like 500 that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it to None to validate all status codes back.

  • semantic_schema – Should we generate any semantic schema for this endpoint?

  • semantic_responses – Should semantic responses be collected from different providers for this endpoint.

  • exclude_semantic_responses – Set of semantic responses status codes that user wants to disable. Overrides controller and settings values. Set it to None to enable all semantic responses back.

  • semantic_auth – Should semantic auth be collected from different providers for this endpoint. Overrides controller and settings values.

  • exclude_semantic_auth – Set of semantic security requirements names that should not be collected. Overrides controller and settings values.

  • extra_responses – Sequence of extra responses that this endpoint can return. Overrides controller and settings values. Set it to None to only use the default response.

  • no_validate_http_spec – Set of http spec validation checks that we disable for this endpoint. Overrides controller and settings values. Set it to None to enable all checks back.

  • error_handler – Callback function to be called when this endpoint faces an exception.

  • parsers – Sequence of types to be used for this endpoint to parse incoming request’s body. All types must be subtypes of Parser. Overrides controller and settings values.

  • renderers – Sequence of types to be used for this endpoint to render response’s body. All types must be subtypes of Renderer. Overrides controller and settings values.

  • validate_negotiation – Should we validate that returned response’s Content-Type header matches the one that we inferred in the negotiation process?

  • auth – Sequence of auth instances to be used for this endpoint. Sync endpoints must use instances of dmr.security.SyncAuth. Async endpoints must use instances of dmr.security.AsyncAuth. Overrides controller and settings values. Set it to None to disable auth for this endpoint.

  • throttling – Sequence of throttle instances to be used for this endpoint. Sync endpoints must use instances of dmr.throttling.SyncThrottle. Async endpoints must use instances of dmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it to None to disable throttling of this endpoint.

  • summary – A short summary of what the operation does. Defaults to the first paragraph of the endpoint’s docstring. Set it to None to have no summary at all.

  • description – A verbose explanation of the operation behavior. Defaults to everything that goes after the first paragraph of the endpoint’s docstring. Set it to None to have no description at all.

  • tags – A sequence of tags for API documentation control. Used to group operations in OpenAPI documentation. Overrides controller-level and router-level tags. Set it to None to have no tags at all.

  • operation_id – Unique string used to identify the operation.

  • deprecated – Declares this operation to be deprecated. Overrides controller-level and router-level values. Set it to False to explicitly mark this operation as not deprecated, even if its controller or router is.

  • security – A sequence of security requirement objects for this operation. Overrides the controller value and security of dmr.openapi.OpenAPIConfig. Set it to None to disable security of this endpoint. It is merged with the requirements generated from auth, but it never affects the runtime auth. Useful to document external security mechanisms, for example, the ones enforced by an HTTP proxy. Used security schemes must be declared as security_schemes in components of dmr.openapi.OpenAPIConfig. See Customizing security.

  • external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to None to have no external docs at all.

  • callbacks – A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. Overrides the controller value. Set it to None to have no callbacks at all.

  • servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to None to have no servers at all.

  • x_extensions – Specification extensions of this operation, keys must start with x-. Set only on this operation: it is never inherited from or merged with x_extensions, which describes the path item, not its operations.

  • links – Possible links to other OpenAPI operations.

  • response_description – Description for the generated response object.

  • ignore_from_spec – If set to True, this endpoint would not be added to the final OpenAPI spec.

  • extras – Extra settings for custom controllers. See Providing extras for @modify and @validate to learn more.

Returns:

The same function with __dmr_payload__ payload instance.

Warning

Do not disable validate_responses unless this is performance critical for you!

Changed in version 0.15.0: modify used to be a function, now it is an instance with lazy method for lazy reusable endpoints.

Changed in version 0.16.0: Removed validate_events parameter, added extras parameter instead. This class is now generic and public.

Validate#

final class dmr.endpoint.ValidateEndpoint(extras_cls: type[_ExtrasT] | EMPTY = EMPTY)[source]#

Decorator to validate responses from endpoints that return HttpResponse.

Apply it to validate important API parts:

>>> from http import HTTPStatus
>>> from django.http import HttpResponse
>>> from dmr import Controller, validate, ResponseSpec
>>> from dmr.plugins.pydantic import PydanticFastSerializer

>>> class TaskController(Controller[PydanticFastSerializer]):
...     @validate(
...         ResponseSpec(
...             return_type=list[int],
...             status_code=HTTPStatus.OK,
...         ),
...     )
...     def post(self) -> HttpResponse:
...         return HttpResponse(b'[1, 2]', status=HTTPStatus.OK)

Response validation can be disabled for extra speed by sending validate_responses falsy parameter or by setting this configuration in your settings.py file:

settings.py#
>>> DMR_SETTINGS = {'validate_responses': False}
Parameters:
  • response – The main response that this endpoint is allowed to return.

  • responses – A collection of other responses that are allowed to be returned from this endpoint.

  • validate_responses – Do we have to run runtime validation of responses for this endpoint? Customizable via global setting, per controller, and per endpoint. Here we only store the per endpoint information.

  • exclude_validate_responses – Set of status codes that we don’t validate, even when validate_responses is enabled. Useful for errors like 500 that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it to None to validate all status codes back.

  • semantic_schema – Should we generate any semantic schema for this endpoint?

  • semantic_responses – Should semantic responses be collected from different providers for this endpoint. Overrides controller and settings values.

  • exclude_semantic_responses – Set of semantic responses status codes that user wants to disable. Overrides controller and settings values. Set it to None to enable all semantic responses back.

  • semantic_auth – Should semantic auth be collected from different providers for this endpoint. Overrides controller and settings values.

  • exclude_semantic_auth – Set of semantic security requirements names that should not be collected. Overrides controller and settings values.

  • no_validate_http_spec – Set of http spec validation checks that we disable for this endpoint. Overrides controller and settings values. Set it to None to enable all checks back.

  • error_handler – Callback function to be called when this endpoint faces an exception.

  • parsers – Sequence of types to be used for this endpoint to parse incoming request’s body. All types must be subtypes of Parser. Overrides controller and settings values.

  • renderers – Sequence of types to be used for this endpoint to render response’s body. All types must be subtypes of Renderer. Overrides controller and settings values.

  • validate_negotiation – Should we validate that returned response’s Content-Type header matches the one that we inferred in the negotiation process?

  • auth – Sequence of auth instances to be used for this endpoint. Sync endpoints must use instances of dmr.security.SyncAuth. Async endpoints must use instances of dmr.security.AsyncAuth. Overrides controller and settings values. Set it to None to disable auth for this endpoint.

  • throttling – Sequence of throttle instances to be used for this endpoint. Sync endpoints must use instances of dmr.throttling.SyncThrottle. Async endpoints must use instances of dmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it to None to disable throttling of this endpoint.

  • summary – A short summary of what the operation does. Defaults to the first paragraph of the endpoint’s docstring. Set it to None to have no summary at all.

  • description – A verbose explanation of the operation behavior. Defaults to everything that goes after the first paragraph of the endpoint’s docstring. Set it to None to have no description at all.

  • tags – A sequence of tags for API documentation control. Used to group operations in OpenAPI documentation. Overrides controller-level and router-level tags. Set it to None to have no tags at all.

  • operation_id – Unique string used to identify the operation.

  • deprecated – Declares this operation to be deprecated. Overrides controller-level and router-level values. Set it to False to explicitly mark this operation as not deprecated, even if its controller or router is.

  • security – A sequence of security requirement objects for this operation. Overrides the controller value and security of dmr.openapi.OpenAPIConfig. Set it to None to disable security of this endpoint. It is merged with the requirements generated from auth, but it never affects the runtime auth. Useful to document external security mechanisms, for example, the ones enforced by an HTTP proxy. Used security schemes must be declared as security_schemes in components of dmr.openapi.OpenAPIConfig. See Customizing security.

  • external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to None to have no external docs at all.

  • callbacks – A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. Overrides the controller value. Set it to None to have no callbacks at all.

  • servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to None to have no servers at all.

  • x_extensions – Specification extensions of this operation, keys must start with x-. Set only on this operation: it is never inherited from or merged with x_extensions, which describes the path item, not its operations.

  • ignore_from_spec – If set to True, this endpoint would not be added to the final OpenAPI spec.

  • extras – Extra settings for custom controllers. See Providing extras for @modify and @validate to learn more.

Returns:

The same function with __dmr_payload__ payload instance.

Warning

Do not disable validate_responses unless this is performance critical for you!

Changed in version 0.15.0: validate used to be a function, now it is an instance with lazy method for lazy reusable endpoints.

Changed in version 0.16.0: Removed validate_events parameter, added extras parameter instead. This class is now generic and public.

__call__(response: ResponseSpec, /, *responses: ResponseSpec, error_handler: EMPTY = EMPTY, validate_responses: bool | EMPTY = EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_schema: bool | EMPTY = EMPTY, semantic_responses: bool | EMPTY = EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_auth: bool | EMPTY = EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None = EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None = EMPTY, parsers: Sequence[Parser] | EMPTY = EMPTY, renderers: Sequence[Renderer] | EMPTY = EMPTY, validate_negotiation: bool | EMPTY = EMPTY, auth: Sequence[Never] | EMPTY | None = EMPTY, throttling: Sequence[Never] | EMPTY | None = EMPTY, summary: str | Promise | EMPTY | None = EMPTY, description: str | Promise | EMPTY | None = EMPTY, tags: Sequence[str] | EMPTY | None = EMPTY, operation_id: str | EMPTY = EMPTY, deprecated: bool | EMPTY = EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None = EMPTY, external_docs: ExternalDocumentation | EMPTY | None = EMPTY, callbacks: Mapping[str, Callback | Reference] | EMPTY | None = EMPTY, servers: Sequence[Server] | EMPTY | None = EMPTY, x_extensions: Mapping[str, Any] | EMPTY = EMPTY, ignore_from_spec: bool | EMPTY = EMPTY, extras: _ExtrasT | EMPTY = EMPTY) → ValidateAnyCallable[source]#
__call__(response: ResponseSpec, /, *responses: ResponseSpec, error_handler: AsyncErrorHandler | EMPTY = EMPTY, validate_responses: bool | EMPTY = EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_schema: bool | EMPTY = EMPTY, semantic_responses: bool | EMPTY = EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_auth: bool | EMPTY = EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None = EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None = EMPTY, parsers: Sequence[Parser] | EMPTY = EMPTY, renderers: Sequence[Renderer] | EMPTY = EMPTY, validate_negotiation: bool | EMPTY = EMPTY, auth: Sequence[AsyncAuth] | EMPTY | None = EMPTY, throttling: Sequence[AsyncThrottle] | EMPTY | None = EMPTY, summary: str | Promise | EMPTY | None = EMPTY, description: str | Promise | EMPTY | None = EMPTY, tags: Sequence[str] | EMPTY | None = EMPTY, operation_id: str | EMPTY = EMPTY, deprecated: bool | EMPTY = EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None = EMPTY, external_docs: ExternalDocumentation | EMPTY | None = EMPTY, callbacks: Mapping[str, Callback | Reference] | EMPTY | None = EMPTY, servers: Sequence[Server] | EMPTY | None = EMPTY, x_extensions: Mapping[str, Any] | EMPTY = EMPTY, ignore_from_spec: bool | EMPTY = EMPTY, extras: _ExtrasT | EMPTY = EMPTY) → ValidateAsyncCallable
__call__(response: ResponseSpec, /, *responses: ResponseSpec, error_handler: SyncErrorHandler | EMPTY = EMPTY, validate_responses: bool | EMPTY = EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_schema: bool | EMPTY = EMPTY, semantic_responses: bool | EMPTY = EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None = EMPTY, semantic_auth: bool | EMPTY = EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None = EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None = EMPTY, parsers: Sequence[Parser] | EMPTY = EMPTY, renderers: Sequence[Renderer] | EMPTY = EMPTY, validate_negotiation: bool | EMPTY = EMPTY, auth: Sequence[SyncAuth] | EMPTY | None = EMPTY, throttling: Sequence[SyncThrottle] | EMPTY | None = EMPTY, summary: str | Promise | EMPTY | None = EMPTY, description: str | Promise | EMPTY | None = EMPTY, tags: Sequence[str] | EMPTY | None = EMPTY, operation_id: str | EMPTY = EMPTY, deprecated: bool | EMPTY = EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None = EMPTY, external_docs: ExternalDocumentation | EMPTY | None = EMPTY, callbacks: Mapping[str, Callback | Reference] | EMPTY | None = EMPTY, servers: Sequence[Server] | EMPTY | None = EMPTY, x_extensions: Mapping[str, Any] | EMPTY = EMPTY, ignore_from_spec: bool | EMPTY = EMPTY, extras: _ExtrasT | EMPTY = EMPTY) → ValidateSyncCallable

Adds the payload to the endpoint function.

extras_cls: type[_ExtrasT] | EMPTY#

Extras class that this decorator instance supports.

Pass it to create a typed decorator: ValidateEndpoint(MyExtras). Controllers using such decorator must use the same extras class in extras.

lazy(provider: _CallableOrClassmethod[_ControllerT, _ValidateDecoratorT]) → _ValidateDecoratorT[source]#

Create lazy endpoint for reusable controller definition.

This provides an agile way to customize all the response details, including headers and cookies spec, response status code, OpenAPI metadata and other things.

See Lazy reusable endpoints for the full example.

Added in version 0.15.0.

dmr.endpoint.validate = ValidateEndpoint(extras_cls=EMPTY)#

Decorator to validate responses from endpoints that return HttpResponse.

Apply it to validate important API parts:

>>> from http import HTTPStatus
>>> from django.http import HttpResponse
>>> from dmr import Controller, validate, ResponseSpec
>>> from dmr.plugins.pydantic import PydanticFastSerializer

>>> class TaskController(Controller[PydanticFastSerializer]):
...     @validate(
...         ResponseSpec(
...             return_type=list[int],
...             status_code=HTTPStatus.OK,
...         ),
...     )
...     def post(self) -> HttpResponse:
...         return HttpResponse(b'[1, 2]', status=HTTPStatus.OK)

Response validation can be disabled for extra speed by sending validate_responses falsy parameter or by setting this configuration in your settings.py file:

settings.py#
>>> DMR_SETTINGS = {'validate_responses': False}
Parameters:
  • response – The main response that this endpoint is allowed to return.

  • responses – A collection of other responses that are allowed to be returned from this endpoint.

  • validate_responses – Do we have to run runtime validation of responses for this endpoint? Customizable via global setting, per controller, and per endpoint. Here we only store the per endpoint information.

  • exclude_validate_responses – Set of status codes that we don’t validate, even when validate_responses is enabled. Useful for errors like 500 that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it to None to validate all status codes back.

  • semantic_schema – Should we generate any semantic schema for this endpoint?

  • semantic_responses – Should semantic responses be collected from different providers for this endpoint. Overrides controller and settings values.

  • exclude_semantic_responses – Set of semantic responses status codes that user wants to disable. Overrides controller and settings values. Set it to None to enable all semantic responses back.

  • semantic_auth – Should semantic auth be collected from different providers for this endpoint. Overrides controller and settings values.

  • exclude_semantic_auth – Set of semantic security requirements names that should not be collected. Overrides controller and settings values.

  • no_validate_http_spec – Set of http spec validation checks that we disable for this endpoint. Overrides controller and settings values. Set it to None to enable all checks back.

  • error_handler – Callback function to be called when this endpoint faces an exception.

  • parsers – Sequence of types to be used for this endpoint to parse incoming request’s body. All types must be subtypes of Parser. Overrides controller and settings values.

  • renderers – Sequence of types to be used for this endpoint to render response’s body. All types must be subtypes of Renderer. Overrides controller and settings values.

  • validate_negotiation – Should we validate that returned response’s Content-Type header matches the one that we inferred in the negotiation process?

  • auth – Sequence of auth instances to be used for this endpoint. Sync endpoints must use instances of dmr.security.SyncAuth. Async endpoints must use instances of dmr.security.AsyncAuth. Overrides controller and settings values. Set it to None to disable auth for this endpoint.

  • throttling – Sequence of throttle instances to be used for this endpoint. Sync endpoints must use instances of dmr.throttling.SyncThrottle. Async endpoints must use instances of dmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it to None to disable throttling of this endpoint.

  • summary – A short summary of what the operation does. Defaults to the first paragraph of the endpoint’s docstring. Set it to None to have no summary at all.

  • description – A verbose explanation of the operation behavior. Defaults to everything that goes after the first paragraph of the endpoint’s docstring. Set it to None to have no description at all.

  • tags – A sequence of tags for API documentation control. Used to group operations in OpenAPI documentation. Overrides controller-level and router-level tags. Set it to None to have no tags at all.

  • operation_id – Unique string used to identify the operation.

  • deprecated – Declares this operation to be deprecated. Overrides controller-level and router-level values. Set it to False to explicitly mark this operation as not deprecated, even if its controller or router is.

  • security – A sequence of security requirement objects for this operation. Overrides the controller value and security of dmr.openapi.OpenAPIConfig. Set it to None to disable security of this endpoint. It is merged with the requirements generated from auth, but it never affects the runtime auth. Useful to document external security mechanisms, for example, the ones enforced by an HTTP proxy. Used security schemes must be declared as security_schemes in components of dmr.openapi.OpenAPIConfig. See Customizing security.

  • external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to None to have no external docs at all.

  • callbacks – A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by the API provider and the expected responses. Overrides the controller value. Set it to None to have no callbacks at all.

  • servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to None to have no servers at all.

  • x_extensions – Specification extensions of this operation, keys must start with x-. Set only on this operation: it is never inherited from or merged with x_extensions, which describes the path item, not its operations.

  • ignore_from_spec – If set to True, this endpoint would not be added to the final OpenAPI spec.

  • extras – Extra settings for custom controllers. See Providing extras for @modify and @validate to learn more.

Returns:

The same function with __dmr_payload__ payload instance.

Warning

Do not disable validate_responses unless this is performance critical for you!

Changed in version 0.15.0: validate used to be a function, now it is an instance with lazy method for lazy reusable endpoints.

Changed in version 0.16.0: Removed validate_events parameter, added extras parameter instead. This class is now generic and public.

Extras#

class dmr.endpoint.Extras[source]#

Abstract base class that describes how any extras should look like.

Extras are extra settings for custom controllers, they are passed as extras= to @modify and @validate. A controller declares which extras it supports by assigning a default instance to extras, the same instance provides controller-level defaults.

Fields that can be omitted on some level should default to EMPTY, required fields are allowed as well.

The type parameter is the type of the built value, it is stored in extras as the first type variable. Use of() to read it with proper types.

Added in version 0.16.0.

abstractmethod classmethod build(from_endpoint: Self | EMPTY, from_controller: Self, controller_cls: type[Controller[BaseSerializer]], builder: EndpointMetadataBuilder) → _BuiltExtrasT_co[source]#

Method that we need to build the final value.

It is called for all endpoints of controllers that support these extras, even when extras= is not passed to the decorator or when there’s no decorator at all.

from_endpoint is the instance passed as extras= to the decorator, or EMPTY when it was not passed. from_controller is the instance set as Controller.extras, it is always present.

We pass controller_cls, so user can take any needed values from there. Or from settings, or from where else. builder provides other context from the whole payload, use merger() to resolve configuration layers the same way other fields do.

The value returned from here will be used in the final metadata. It is called during the import-time and can be slow.

classmethod of(controller: Controller[BaseSerializer]) → _BuiltExtrasT_co[source]#

Get the built extras of the endpoint that serves the current request.

This is the typed way to read extras. Raises EndpointMetadataError when controller does not use these extras.

Lazy endpoints#

class dmr.endpoint.ModifySyncCallable(*args, **kwargs)[source]#

Type that represents @modify decorator for sync functions.

Features:

  • Does not allow using HttpResponse as the return annotation

  • Does not allow applying the decorator on async endpoints

class dmr.endpoint.ModifyAsyncCallable(*args, **kwargs)[source]#

Type that represents @modify decorator for async functions.

Features:

  • Does not allow using HttpResponse as the return annotation

  • Does not allow applying the decorator on sync endpoints

class dmr.endpoint.ModifyAnyCallable(*args, **kwargs)[source]#

Type that represents @modify decorator for any function.

Features:

  • Does not allow using HttpResponse as the return annotation

  • Does not allow specifying sync / async specific parts

class dmr.endpoint.ValidateSyncCallable(*args, **kwargs)[source]#

Type that represents @validate decorator for sync functions.

Features:

  • Does not allow using anything other than HttpResponse as the return annotation

  • Does not allow applying the decorator on async endpoints

Added in version 0.15.0.

class dmr.endpoint.ValidateAsyncCallable(*args, **kwargs)[source]#

Type that represents @validate decorator for async functions.

Features:

  • Does not allow using anything other

    than HttpResponse as the return annotation

  • Does not allow applying the decorator on sync endpoints

Added in version 0.15.0.

class dmr.endpoint.ValidateAnyCallable(*args, **kwargs)[source]#

Type that represents @modify decorator for any function.

Features:

  • Does not allow using anything other

    than HttpResponse as the return annotation

  • Does not allow specifying sync / async specific parts

Added in version 0.15.0.

Meta mixins#

class dmr.options_mixins.MetaMixin[source]#

Mixin that provides default meta method or OPTIONS http method.

Use it for sync controllers.

It just returns the list of allowed methods. Use it as a mixin with the dmr.controller.Controller type:

>>> from dmr import Controller
>>> from dmr.options_mixins import MetaMixin
>>> from dmr.plugins.pydantic import PydanticSerializer

>>> class SupportsOptionsHttpMethod(
...     MetaMixin,
...     Controller[PydanticSerializer],
... ): ...
meta() → HttpResponse[source]#

Default sync implementation for OPTIONS http method.

class dmr.options_mixins.AsyncMetaMixin[source]#

Mixin that provides default meta method or OPTIONS http method.

Use it for async controllers.

It just returns the list of allowed methods. Use it as a mixin with the dmr.controller.Controller type:

>>> from dmr import Controller
>>> from dmr.options_mixins import AsyncMetaMixin
>>> from dmr.plugins.pydantic import PydanticSerializer

>>> class SupportsOptionsHttpMethod(
...     AsyncMetaMixin,
...     Controller[PydanticSerializer],
... ): ...
async meta() → HttpResponse[source]#

Default async implementation for OPTIONS http method.