Validation#

Validation#

final class dmr.validation.ModifyEndpointPayload(*, summary: str | Promise | EMPTY | None, description: str | Promise | EMPTY | None, tags: Sequence[str] | EMPTY | None, operation_id: str | EMPTY, deprecated: bool | EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None, external_docs: ExternalDocumentation | EMPTY | None, callbacks: Mapping[str, Callback | Reference] | EMPTY | None, servers: Sequence[Server] | EMPTY | None, x_extensions: Mapping[str, Any] | EMPTY, ignore_from_spec: bool | EMPTY, extras: Extras[Any] | EMPTY, extras_cls: type[Extras[Any]] | EMPTY, validate_responses: bool | EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None, semantic_schema: bool | EMPTY, semantic_responses: bool | EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None, semantic_auth: bool | EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None, error_handler: Callable[[Endpoint, Controller[BaseSerializer], Exception], HttpResponse] | Callable[[Endpoint, Controller[BaseSerializer], Exception], Awaitable[HttpResponse]] | EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None, parsers: Sequence[Parser] | EMPTY, renderers: Sequence[Renderer] | EMPTY, validate_negotiation: bool | EMPTY, auth: Sequence[SyncAuth] | Sequence[AsyncAuth] | EMPTY | None, throttling: Sequence[SyncThrottle] | Sequence[AsyncThrottle] | EMPTY | None, responses: Sequence[ResponseSpec] | EMPTY | None, status_code: HTTPStatus | EMPTY, headers: Mapping[str, NewHeader | HeaderSpec] | EMPTY, cookies: Mapping[str, NewCookie | CookieSpec] | EMPTY, response_description: str | EMPTY, links: Mapping[str, Link | Reference] | EMPTY)[source]#

Payload created by @modify.

final class dmr.validation.ValidateEndpointPayload(*, summary: str | Promise | EMPTY | None, description: str | Promise | EMPTY | None, tags: Sequence[str] | EMPTY | None, operation_id: str | EMPTY, deprecated: bool | EMPTY, security: Sequence[SecurityRequirement] | EMPTY | None, external_docs: ExternalDocumentation | EMPTY | None, callbacks: Mapping[str, Callback | Reference] | EMPTY | None, servers: Sequence[Server] | EMPTY | None, x_extensions: Mapping[str, Any] | EMPTY, ignore_from_spec: bool | EMPTY, extras: Extras[Any] | EMPTY, extras_cls: type[Extras[Any]] | EMPTY, validate_responses: bool | EMPTY, exclude_validate_responses: Set[HTTPStatus] | EMPTY | None, semantic_schema: bool | EMPTY, semantic_responses: bool | EMPTY, exclude_semantic_responses: Set[HTTPStatus] | EMPTY | None, semantic_auth: bool | EMPTY, exclude_semantic_auth: Set[str] | EMPTY | None, error_handler: Callable[[Endpoint, Controller[BaseSerializer], Exception], HttpResponse] | Callable[[Endpoint, Controller[BaseSerializer], Exception], Awaitable[HttpResponse]] | EMPTY, no_validate_http_spec: Set[HttpSpec] | EMPTY | None, parsers: Sequence[Parser] | EMPTY, renderers: Sequence[Renderer] | EMPTY, validate_negotiation: bool | EMPTY, auth: Sequence[SyncAuth] | Sequence[AsyncAuth] | EMPTY | None, throttling: Sequence[SyncThrottle] | Sequence[AsyncThrottle] | EMPTY | None, responses: list[ResponseSpec] | EMPTY)[source]#

Payload created by @validate.

classmethod implicit() → ValidateEndpointPayload[source]#

Create a payload for endpoints that return HttpResponse.

Such endpoints do not have to use @validate explicitly, when responses are defined on the controller or settings level. All values are the same as @validate defaults, except responses which is EMPTY and not an explicit [], so the controller and settings levels are used.

class dmr.validation.payload.PayloadBuilder(func: Callable[[...], Any])[source]#

Builds the payload from the endpoint function and the controller class.

Added in version 0.15.0.

__call__(controller_cls: type[Controller[BaseSerializer]]) → ValidateEndpointPayload | ModifyEndpointPayload | None[source]#

Processes the callable payloads from modify.lazy and others.

Serialization#

class dmr.serializer.BaseSerializer[source]#

Abstract base class for data serialization.

What serializer does?

  1. It provides serialization and deserialization hooks for parser and renderer. So different parsers and renderers will work similarly. This way you can modify all the serialization logic in one place and not adjust all possible parsers or renderers

  2. It provides validation for raw python data, see dmr.serializer.BaseSerializer.from_python() method

  3. It provides serialization for related complex utility objects like validation errors and responses that don’t have .content attribute. For example: file and sse responses

validation_error#

Exception type that is used for validation errors. Required to be set in subclasses.

Type:

ClassVar[type[Exception]]

optimizer#

Endpoint optimizer. Type that pre-compiles / creates / caches models in import time. Required to be set in subclasses.

Type:

ClassVar[type[dmr.serializer.BaseEndpointOptimizer]]

schema_generator#

Generates schema and schema names for the OpenAPI.

Type:

ClassVar[type[dmr.serializer.BaseSchemaGenerator]]

abstractmethod classmethod build_context_model(name: str, fields: Mapping[str, ContextField]) → ContextModel[source]#

Build the best model to parse the whole request context at once.

All components of an endpoint are parsed in a single from_python() call. This method builds the model for that call. Each serializer picks the fastest model type it can validate: it can be a typing.TypedDict, a dataclass, a msgspec.Struct, or anything else.

Fields with defaults must not be required by the model. Default values must be used as-is, without any copies or default factories, because they are the real python defaults of the endpoint function. Use context_field_tuples() to get them in the form that most model constructors accept.

Parameters:
  • name – Name of the model to build. Not really important.

  • fields – Mapping of field names to their annotations and defaults.

Returns:

Model and the way to convert its instances into keyword arguments.

Added in version 0.16.0.

abstractmethod classmethod deserialize(buffer: bytes | bytearray, *, parser: Parser, request: HttpRequest, model: TypeForm[Any]) → Any[source]#

Convert json bytestring to structured data.

classmethod deserialize_hook(target_type: type[Any], to_deserialize: Any) → Any[source]#

Customize how some objects are deserialized from json.

Only add types that are common for all potential plugins here. Should be called inside deserialize().

abstractmethod classmethod from_python(unstructured: Any, model: TypeForm[Any], *, strict: bool | None, extra_namespace: Mapping[str, Any] | None = None) → Any[source]#

Parse unstructured data from python primitives into model.

Raises cls.validation_error when something cannot be parsed.

Parameters:
  • unstructured – Python objects to be parsed / validated.

  • model – Python type to serve as a model. Can be any type hints that user can theoretically supply. Depends on the serialization plugin.

  • strict – Whether we use more strict validation rules. For example, it is fine for a request validation to be less strict in some cases and allow type coercition. But, response types need to be strongly validated.

  • extra_namespace – Optional namespace to load type annotations from. It is useful, when using stringified or lazy type annotations.

Returns:

Structured and validated data.

Changed in version 0.13.0: Added extra_namespace parameter.

abstractmethod classmethod serialize(structure: Any, *, renderer: Renderer) → bytes[source]#

Convert structured data to json bytestring.

classmethod serialize_hook(to_serialize: Any) → Any[source]#

Customize how some objects are serialized into json.

Only add types that are common for all potential plugins here. Should be called inside serialize().

abstractmethod classmethod serialize_validation_error(exc: Exception) → list[ErrorDetail][source]#

Convert specific serializer’s validation errors into simple python data.

Parameters:

exc – A serialization exception to be serialized into simpler type. For example, pydantic has a complex pydantic_core.ValidationError type. That can’t be converted to a simpler error message easily.

Returns:

Simple python object - exception converted to json.

abstractmethod classmethod to_python(structured: Any) → Any[source]#

Unstructure structured data from a model into Python primitives.

Parameters:

structured – Model instance.

Returns:

Unstructured data.

classmethod validate(controller_cls: type[Controller[BaseSerializer]], metadata: EndpointMetadata) → None[source]#

Validate that this serializer can serve the endpoint at import time.

It is called once per endpoint, after all metadata fields are fully built, so parsers, renderers, components, and everything else can be inspected. Override this method to enforce serializer-specific constraints, like supported parsers and renderers or supported components. Raise EndpointMetadataError if the serializer is used incorrectly.

By default all endpoints are supported.

Changed in version 0.16.0: Replaces is_supported method, which only received a single parser or renderer and returned a boolean.

class dmr.serializer.BaseEndpointOptimizer[source]#

Plugins might often need to run some specific preparations for endpoints.

To achieve that we provide an explicit API for that.

abstractmethod classmethod optimize_endpoint(metadata: EndpointMetadata) → None[source]#

Optimize the endpoint.

Parameters:

metadata – Endpoint metadata to optimize.

class dmr.endpoint.SerializerContext(func: Callable[[...], Any], controller_cls: type[Controller[BaseSerializer]], type_annotations: dict[str, Any])[source]#

Parse and bind request components for a controller.

This context collects raw data for all registered components, validates the combined payload in a single call using a cached model that the serializer builds, and then binds the parsed values back to the controller.

Components with default values return them when a request has no data for them, so the endpoint receives their real python defaults.

strict_validation#

Whether or not to validate payloads in strict mode. Strict mode in some serializers does not allow implicit type conversions. Defaults to None, which means that we decide on a per-field basis if it is set, if not then on a per-model basis.

Type:

ClassVar[bool | None]

Changed in version 0.16.0: Models are now built by serializer.build_context_model, defaults of component parameters are now supported.

Changed in version 0.17.0: Now we can optimize the parsing logic in import time.

component_builder_cls#

alias of ComponentParserBuilder

class dmr.serializer.BaseSchemaGenerator[source]#

Generates JSON schema by the native serializer API.

abstractmethod classmethod get_schema(model: TypeForm[Any], ref_template: str, *, used_for_response: bool = False) → tuple[dict[str, Any], dict[str, Any]][source]#

Provide JSON schema / OpenAPI spec for the given model.

Parameters:
  • model – Model to generate JSON schema for.

  • ref_template – Reference template to use for the references.

  • used_for_response – Is this schema used for the response or request.

Raises:

Exception – when schema cannot be built. Can be any Exception subclass instance.

abstractmethod classmethod schema_name(model: TypeForm[Any]) → str | None[source]#

Return a schema name for a model, if it exists.

It is done directly by the serializer, we don’t store any specific logic for it.

final class dmr.serializer.ContextField(annotation: TypeForm[Any], default: Any = EMPTY)[source]#

Single field of a context model to be built by a serializer.

Added in version 0.16.0.

annotation: TypeForm[Any]#

Type annotation to parse the field into.

default: Any#

Default value of the field, used when the field is missing.

EMPTY means that the field is required. It is always the exact object that the endpoint has as its default, we never copy it or wrap it into any factories.

final class dmr.serializer.ContextModel(model: TypeForm[Any], to_kwargs: Callable[[Any], dict[str, Any]] | None = None)[source]#

Model that a serializer has built to parse the whole request context.

Added in version 0.16.0.

model: TypeForm[Any]#

Any type that BaseSerializer.from_python() can parse into.

to_kwargs: Callable[[Any], dict[str, Any]] | None#

Converts a parsed model instance into a mapping of field names to values.

None means that BaseSerializer.from_python() already returns a mapping for this model, so no conversion is needed.

dmr.serializer.context_field_tuples(fields: Mapping[str, ContextField]) → list[tuple[Any, ...]][source]#

Convert context fields into tuples that model constructors accept.

Both dataclasses.make_dataclass() and msgspec.defstruct() accept (name, type) tuples for required fields and (name, type, default) tuples for fields with defaults. Fields with defaults always go after the fields without them, just like in regular function signatures.

Added in version 0.16.0.

class dmr.components.ComponentParserBuilder(func: Callable[[...], Any], controller_cls: type[Controller[BaseSerializer]])[source]#

Find the component parser types in the MRO and find model types for them.

Validates that component parsers can’t have type vars as models at this point.

Changed in version 0.16.0: Now also finds default values of component parameters. Component annotations hidden inside other types, like Body[Model] | None, are now rejected.

__call__(type_annotations: dict[str, Any]) → list[ComponentParserSpec][source]#

Run the building process, infer type vars if needed.

defaults_cls#

alias of FunctionDefaults

type_var_inference_cls#

alias of TypeVarInference

final class dmr.components.ComponentParserSpec(parser: ComponentParser, model: TypeForm[Any], model_meta: tuple[Any, ...], default: Any = EMPTY)[source]#

Describes a single component parser of an endpoint.

Changed in version 0.16.0: Now it is a named tuple with the default field, previously it was a regular tuple of three elements. Moved from dmr.metadata to dmr.components.

default: Any#

Default value of the endpoint parameter for this component.

EMPTY means that there’s no default value, so the component data must be present in every request.

model: TypeForm[Any]#

Model to parse the component data into.

model_meta: tuple[Any, ...]#

Extra typing.Annotated metadata of the component.

parser: ComponentParser#

Component parser instance, like BodyComponent.

class dmr.components.FunctionDefaults(func: Callable[[...], Any])[source]#

Find default values of all function parameters.

Both regular and keyword-only defaults are supported. Component parameters with defaults are optional: when a request has no data for such a component, the default value is used as-is, without any parsing.

Added in version 0.16.0.

__call__() → Mapping[str, Any][source]#

Return a mapping of parameter names to their defaults.

Parameters without defaults map to EMPTY.

get_signature() → Signature[source]#

Method that can be easily customized to change the signature.

Validators#

Settings#

class dmr.validation.settings.SettingsValidator(*, serializer: type[BaseSerializer])[source]#

Validates defined settings once.

__call__() → None[source]#

Collect and validate settings.

Endpoint#

class dmr.validation.endpoint_metadata.EndpointMetadataBuilder(*, payload: ValidateEndpointPayload | ModifyEndpointPayload | None, controller_cls: type[Controller[BaseSerializer]], func: Callable[[...], Any], metadata_cls: type[EndpointMetadata], response_modification_cls: type[ResponseModification], metadata_merger_cls: type[MetadataMerger], component_parsers: list[ComponentParserSpec], type_annotations: dict[str, Any])[source]#

Validate the metadata definition.

It is done during import-time only once, so it can be not blazing fast. It is better to be precise here than to be fast.

Here we only do structure and required validation. All semantic validation will be performed later on.

Metadata will NOT be considered ready after running this process.

__call__() → EndpointMetadata[source]#

Do the validation.

build_semantic_schema() → bool[source]#

Resolve the semantic_schema flag for this endpoint.

It is public, because other flags can default to this one.

Added in version 0.16.0.

build_validate_responses() → bool[source]#

Resolve the validate_responses flag for this endpoint.

It is public, because other flags can default to this one.

Added in version 0.16.0.

merger(field_name: str) → MetadataMerger[source]#

Create a merger for the given metadata field.

Use it to resolve endpoint, controller, and settings layers the same way built-in fields are resolved.

Added in version 0.16.0.

class dmr.validation.endpoint_metadata.EndpointMetadataValidator(*, metadata: EndpointMetadata, metadata_merger_cls: type[MetadataMerger])[source]#

Builds responses for the endpoint metadata.

Runs semantic validation.

Metadata will be considered ready after running this process.

__call__(func: Callable[[...], Any], payload: ValidateEndpointPayload | ModifyEndpointPayload | None, *, controller_cls: type[Controller[BaseSerializer]]) → None[source]#

Collect and validate all responses.

response_list_validator_cls#

alias of _ResponseListValidator

class dmr.validation.metadata_merger.MetadataMerger(*, field_name: str)[source]#

Define how endpoint, controller, and settings values are resolved.

Every configurable field of the endpoint metadata is resolved with a single call to one of these methods. All layers are passed at once, from the most specific one (endpoint) to the least specific one (settings), so field_name can be used to change how a specific field is resolved.

By default, nothing is merged: the first layer with an explicit value wins. Only EMPTY is not explicit: None, empty collections, and all other values are used as-is. Override this class and set it as metadata_merger_cls to change this. For example, to merge auth from all layers:

Added in version 0.16.0.

empty_to_none(layer: _LayerT | EMPTY) → _LayerT | None[source]#

Convert EMPTY to None for the resolved metadata.

Resolved metadata does not have the “not set” state anymore, so None is used there for missing optional values. It is used for endpoint-only fields, which have a single layer.

first_defined(*layers: _LayerT | EMPTY | None) → _LayerT | EMPTY | None[source]#

Return the first explicitly defined configuration layer.

It is used for collections. Only EMPTY is not explicit, the next layer is used instead of it. It returns EMPTY if no layer has an explicit value.

None is an explicit value, it disables all less specific layers. Empty collections like [] and () are explicit values too, they are taken literally: “nothing on this layer”, they also disable all less specific layers.

first_set(*layers: _LayerT | EMPTY) → _LayerT | EMPTY[source]#

Return the first configuration layer that is not EMPTY.

Unlike first_defined(), it is used for scalar values, where False, 0, and None are real values. It returns EMPTY if all layers are EMPTY.

not_empty(to_check: _LayerT | EMPTY) → _LayerT[source]#

Check that a value is not empty.

Controller#

class dmr.validation.controller.ControllerValidator[source]#

Validates that controller is created correctly.

__call__(controller: type[Controller[BaseSerializer]]) → bool | None[source]#

Run the validation.

Response#

class dmr.validation.response.ResponseValidator(metadata: EndpointMetadata, serializer: type[BaseSerializer])[source]#

Response validator.

Can validate responses that return raw data as well as real HttpResponse that are returned from endpoints.

validate_modification(endpoint: Endpoint, controller: Controller[BaseSerializer], structured: Any) → HttpResponseBase[source]#

Validate structured data before dumping it to json.

Changed in version 0.16.0: Now returns HttpResponseBase object directly. Removed ValidatedModification creation.

validate_response(endpoint: Endpoint, controller: Controller[BaseSerializer], response: _ResponseT) → _ResponseT[source]#

Validate response based on provided schema.

Changed in version 0.15.0: Respects exclude_validate_responses.