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.Viewsubclass 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
Noneto 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.
- exclude_validate_responses#
Set of status codes that we don’t validate, even when
validate_responsesis enabled. Useful for errors like500that can be raised from anywhere and that you might not want to describe. Overrides the settings value, can be overridden per endpoint. Set it toNoneto 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?
- semantic_responses#
Should semantic responses be collected from different providers for all endpoints in this class.
- exclude_semantic_responses#
Set of semantic responses that user wants to disable. Overrides the settings value, can be overridden per endpoint. Set it to
Noneto 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.
- 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 toNoneto 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 includesmeta.- 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-Typeheader matches the one that we inferred in the negotiation process?
- 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 ofdmr.security.AsyncAuth. Overrides the settings value, can be overridden per endpoint. Set it toNoneto 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 ofdmr.throttling.AsyncThrottle. Overrides the settings value, can be overridden per endpoint. Set it toNoneto 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_endpointsinstances. You can also set it toTrueexplicitly 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 declareis_abstractthemselves become concrete again. Abstract controllers cannot be routed,as_viewraisesEndpointMetadataErrorfor them.- Type:
ClassVar[bool]
- extras#
Default extras instance for this controller. Setting it enables
extras=in@modifyand@validatefor all endpoints and provides controller-level defaults.EMPTYmeans 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
Trueby 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. IsFalseby default. Users should make use of authentication indjango-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
Noneto have no summary at all.
- 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
Noneto have no description at all.
- 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
Noneto 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
securityofdmr.openapi.OpenAPIConfig, can be overridden per endpoint. Set it toNoneto disablesecurityfor this controller. It is merged with the requirements generated fromauth, 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 assecurity_schemesincomponentsofdmr.openapi.OpenAPIConfig. See Customizing security.
- servers#
An alternative servers array to service all operations in this controller. Can be overridden per endpoint. Set it to
Noneto 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.
- external_docs#
Additional external documentation for all operations in this controller. Can be overridden per endpoint. Set it to
Noneto 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
Noneto 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
PathItemof this controller, keys must start withx-. 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. Usex_extensionsofmodify()orvalidate()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
HttpRequestinstance.
- args#
Path positional parameters of the request.
Changed in version 0.16.0: Explicit
is_abstractdefinitions are now respected: abstract controllers do not build any endpoints. Addeddeprecated,external_docs,callbacks, andx_extensions.serversis now resolved per endpoint and dumped on operations, not on the path item.- 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 indjango-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 nextas_viewin 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
EndpointMetadataErrorinstead of silently returning a broken view.Controllers now set
login_requiredtoFalseby default in order to exempt controllers from Django’sLoginRequiredMiddleware.
- 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_itemtoget_schemaNow allows to return
Noneto ignore whole path items from OpenAPI schema
Changed in version 0.16.0:
summaryanddescriptionare now parsed from the controller’s docstring when they are not set explicitly. Changed path and pattern parameters to be route_metadata instead.serversis 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_allowedraises 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
optionsyou should define our ownmetamethod:>>> 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
metamethod is not provided for you. If you want to supportOPTIONShttp 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 setheadmethod 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_responsemethod with a siglightly different signature and semantics.Should be always used instead of using raw
django.http.HttpResponseobjects. 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.HttpResponseobjects. 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
HttpResponseBaseobjects from modifications, nowResponseValidatorreturns full responses.funcis 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.
- type_annotations#
Unmodified unnotations of the endpoint function, returned by the resolution method.
- 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.
- 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:
- modification#
Default modifications that are applied to the returned data. Can be
None, when@validateis used.- Type:
- 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:
- parsers#
List of instances to be used for this endpoint to parse incoming request’s body. All instances must be of subtypes of
Parser.
- renderers#
List of instances to be used for this endpoint to render response’s body. All instances must be of subtypes of
Renderer.
- validate_negotiation#
Should we validate that returned response’s
Content-Typeheader matches the one that we inferred in the negotiation process?- Type:
- 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 ofdmr.security.AsyncAuth. When set it toNoneit 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 ofdmr.throttling.AsyncThrottle. Set it toNoneto 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_responsesis enabled.- Type:
- no_validate_http_spec#
Set of checks that user wants to disable for validation in this endpoint.
- allowed_http_methods#
Set of extra HTTP methods that are allowed for this endpoint.
- exclude_semantic_responses#
Set of semantic responses that user wants to disable.
- Type:
- 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,
EMPTYmeans that router-level tags are used during the schema generation.
- deprecated#
Declares this operation to be deprecated. Already resolved from the endpoint and the controller,
EMPTYmeans that the router-level value is used during the schema generation.
- 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
securityofOpenAPIConfigfrom the settings: the first explicitly defined level wins. They are merged with the requirements fromauthduring the schema generation. When set toNoneit 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.
- 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.
- x_extensions#
Specification extensions of this operation, keys must start with
x-. Endpoint-only field, it is never resolved from the controller:Controller.x_extensionsdescribes the path item.
- ignore_from_spec#
If set to
True, this endpoint would not be added to the final OpenAPI spec.- Type:
- extras#
Extra settings for custom controllers, built by
build()ofextras. It isNonewhen the controller does not support extras. See Providing extras for @modify and @validate to learn more.- Type:
dmr.metadata._ExtrasT
methodcan be a custom name, not specified inhttp.HTTPMethodenum, whenallowed_http_methodsis used for endpoint definition. This might be useful for cases like when you need to define a method likequery, 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.
- 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
Controllerlikechecks=. And you can subclassEndpointMetadatato also containchecksfield and override this method to also include response specs from this field.Define
semantic_responsestoFalseon 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
Endpointthat was used for this request.When strict is passed and request has no endpoint, we raise
AttributeError. This can happen for405responses, 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_responsesis enabled. Useful for errors like500that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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
Noneto 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-Typeheader 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 ofdmr.security.AsyncAuth. Overrides controller and settings values. Set it toNoneto 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 ofdmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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
Noneto 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
Falseto 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
securityofdmr.openapi.OpenAPIConfig. Set it toNoneto disablesecurityof this endpoint. It is merged with the requirements generated fromauth, 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 assecurity_schemesincomponentsofdmr.openapi.OpenAPIConfig. See Customizing security.external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to
Noneto 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
Noneto have no callbacks at all.servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to
Noneto 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 withx_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_responsesunless this is performance critical for you!Changed in version 0.15.0:
modifyused to be a function, now it is an instance withlazymethod 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 inextras.
- 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_responsesis enabled. Useful for errors like500that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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
Noneto 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-Typeheader 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 ofdmr.security.AsyncAuth. Overrides controller and settings values. Set it toNoneto 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 ofdmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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
Noneto 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
Falseto 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
securityofdmr.openapi.OpenAPIConfig. Set it toNoneto disablesecurityof this endpoint. It is merged with the requirements generated fromauth, 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 assecurity_schemesincomponentsofdmr.openapi.OpenAPIConfig. See Customizing security.external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to
Noneto 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
Noneto have no callbacks at all.servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to
Noneto 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 withx_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_responsesunless this is performance critical for you!Changed in version 0.15.0:
modifyused to be a function, now it is an instance withlazymethod 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.pyfile: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_responsesis enabled. Useful for errors like500that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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-Typeheader 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 ofdmr.security.AsyncAuth. Overrides controller and settings values. Set it toNoneto 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 ofdmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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
Noneto 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
Falseto 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
securityofdmr.openapi.OpenAPIConfig. Set it toNoneto disablesecurityof this endpoint. It is merged with the requirements generated fromauth, 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 assecurity_schemesincomponentsofdmr.openapi.OpenAPIConfig. See Customizing security.external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to
Noneto 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
Noneto have no callbacks at all.servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to
Noneto 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 withx_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_responsesunless this is performance critical for you!Changed in version 0.15.0:
validateused to be a function, now it is an instance withlazymethod 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 inextras.
- 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.pyfile: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_responsesis enabled. Useful for errors like500that can be raised from anywhere and that you might not want to describe. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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-Typeheader 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 ofdmr.security.AsyncAuth. Overrides controller and settings values. Set it toNoneto 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 ofdmr.throttling.AsyncThrottle. Overrides controller and settings values. Set it toNoneto 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
Noneto 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
Noneto 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
Noneto 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
Falseto 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
securityofdmr.openapi.OpenAPIConfig. Set it toNoneto disablesecurityof this endpoint. It is merged with the requirements generated fromauth, 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 assecurity_schemesincomponentsofdmr.openapi.OpenAPIConfig. See Customizing security.external_docs – Additional external documentation for this operation. Overrides the controller value. Set it to
Noneto 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
Noneto have no callbacks at all.servers – An alternative servers sequence to service this operation. Overrides the controller value. Set it to
Noneto 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 withx_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_responsesunless this is performance critical for you!Changed in version 0.15.0:
validateused to be a function, now it is an instance withlazymethod 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@modifyand@validate. A controller declares which extras it supports by assigning a default instance toextras, 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
extrasas the first type variable. Useof()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, orEMPTYwhen it was not passed. from_controller is the instance set asController.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. RaisesEndpointMetadataErrorwhen controller does not use these extras.
Lazy endpoints#
- class dmr.endpoint.ModifySyncCallable(*args, **kwargs)[source]#
Type that represents
@modifydecorator for sync functions.Features:
Does not allow using
HttpResponseas the return annotationDoes not allow applying the decorator on async endpoints
- class dmr.endpoint.ModifyAsyncCallable(*args, **kwargs)[source]#
Type that represents
@modifydecorator for async functions.Features:
Does not allow using
HttpResponseas the return annotationDoes not allow applying the decorator on sync endpoints
- class dmr.endpoint.ModifyAnyCallable(*args, **kwargs)[source]#
Type that represents
@modifydecorator for any function.Features:
Does not allow using
HttpResponseas the return annotationDoes not allow specifying sync / async specific parts
- class dmr.endpoint.ValidateSyncCallable(*args, **kwargs)[source]#
Type that represents
@validatedecorator for sync functions.Features:
Does not allow using anything other than
HttpResponseas the return annotationDoes not allow applying the decorator on async endpoints
Added in version 0.15.0.
Meta mixins#
- class dmr.options_mixins.MetaMixin[source]#
Mixin that provides default
metamethod orOPTIONShttp method.Use it for sync controllers.
It just returns the list of allowed methods. Use it as a mixin with the
dmr.controller.Controllertype:>>> 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
OPTIONShttp method.
- class dmr.options_mixins.AsyncMetaMixin[source]#
Mixin that provides default
metamethod orOPTIONShttp method.Use it for async controllers.
It just returns the list of allowed methods. Use it as a mixin with the
dmr.controller.Controllertype:>>> 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
OPTIONShttp method.