OpenAPI Reference

Objects

dmr.openapi.objects.Callback

alias of dict[str, PathItem | Reference]

class dmr.openapi.objects.Components(*, schemas: dict[str, Schema] | None = None, responses: dict[str, Response | Reference] | None = None, parameters: dict[str, Parameter | Reference] | None = None, examples: dict[str, Example | Reference] | None = None, request_bodies: dict[str, RequestBody | Reference] | None = None, headers: dict[str, Header | Reference] | None = None, security_schemes: dict[str, SecurityScheme | Reference] | None = None, links: dict[str, Link | Reference] | None = None, callbacks: dict[str, Callback | Reference] | None = None, path_items: dict[str, PathItem | Reference] | None = None)[source]

Holds a set of reusable objects for different aspects of the OAS.

All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object.

class dmr.openapi.objects.Contact(*, name: str | None = None, url: str | None = None, email: str | None = None)[source]

Contact information for the exposed API.

class dmr.openapi.objects.Discriminator(*, property_name: str, mapping: dict[str, str] | None = None)[source]

Discriminator Object.

When request bodies or response payloads may be one of a number of different schemas, a discriminator object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the document of an alternative schema based on the value associated with it.

class dmr.openapi.objects.Encoding(*, content_type: str | None = None, headers: dict[str, Header | Reference] | None = None, style: str | None = None, explode: bool | None = None, allow_reserved: bool | None = None)[source]

A single encoding definition applied to a single schema property.

class dmr.openapi.objects.Example(*, summary: str | None = None, description: str | None = None, value: Any | None = None, external_value: str | None = None)[source]

Example Object.

In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.

class dmr.openapi.objects.ExternalDocumentation(*, url: str, description: str | None = None)[source]

Allows referencing an external resource for extended documentation.

class dmr.openapi.objects.Header(*, schema: Schema | Reference | None = None, description: str | None = None, required: bool | None = None, deprecated: bool | None = None, style: str | None = None, explode: bool | None = None, example: Any | None = None, examples: dict[str, Example | Reference] | None = None, content: dict[str, MediaType] | None = None)[source]

Header Object.

The Header Object follows the structure of the Parameter Object with the following changes: All traits that are affected by the location MUST be applicable to a location of header (for example, style).

class dmr.openapi.objects.Info(*, title: str, version: str, summary: str | None = None, description: str | None = None, terms_of_service: str | None = None, contact: Contact | None = None, license: License | None = None)[source]

The Info object provides metadata about the API.

The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience.

class dmr.openapi.objects.License(*, name: str, identifier: str | None = None, url: str | None = None)[source]

License information for the exposed API.

The Link object represents a possible design-time link for a response.

The presence of a link does not guarantee the caller’s ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations.

final class dmr.openapi.objects.MediaTypeMetadata(*, example: Any | None = None, examples: dict[str, Example | Reference] | None = None, encoding: dict[str, Encoding] | None = None, item_encoding: Encoding | None = None, prefix_encoding: Encoding | None = None)[source]

Media type metadata to be set on a request body.

__hash__() int[source]

Hash the dataclass in a safe way.

class dmr.openapi.objects.MediaType(*, schema: Reference | Schema | None = None, example: Any | None = None, examples: dict[str, Example | Reference] | None = None, encoding: dict[str, Encoding] | None = None, item_schema: Reference | Schema | None = None, item_encoding: Encoding | None = None, prefix_encoding: Encoding | None = None)[source]

Media Type Object.

Each Media Type Object provides schema and examples for the media type identified by its key.

__post_init__() None[source]

Validate the object.

class dmr.openapi.objects.OAuthFlow(*, authorization_url: str | None = None, token_url: str | None = None, refresh_url: str | None = None, scopes: dict[str, str] | None = None)[source]

Configuration details for a supported OAuth Flow.

class dmr.openapi.objects.OAuthFlows(*, implicit: OAuthFlow | None = None, password: OAuthFlow | None = None, client_credentials: OAuthFlow | None = None, authorization_code: OAuthFlow | None = None)[source]

Allows configuration of the supported OAuth Flows.

class dmr.openapi.objects.OpenAPI(*, info: Info, openapi: str, json_schema_dialect: str | None = None, servers: list[Server] | None = None, paths: Paths | None = None, webhooks: dict[str, PathItem | Reference] | None = None, components: Components | None = None, security: list[SecurityRequirement] | None = None, tags: list[Tag] | None = None, external_docs: ExternalDocumentation | None = None)[source]

This is the root object of the OpenAPI document.

convert(*, skip_validation: bool = False) dict[str, Any][source]

Convert the object to OpenAPI schema dictionary.

Runs validation if 'django-modern-rest[openapi]' is installed and skip_validation is falsy.

final class dmr.openapi.objects.OpenAPIFormat(*values)[source]

OpenAPI format.

final class dmr.openapi.objects.OpenAPIType(*values)[source]

OpenAPI types.

class dmr.openapi.objects.Operation(*, tags: list[str] | None = None, summary: str | None = None, description: str | None = None, external_docs: ExternalDocumentation | None = None, operation_id: str | None = None, parameters: list[Parameter | Reference] | None = None, request_body: RequestBody | Reference | None = None, responses: Responses | None = None, callbacks: dict[str, Callback | Reference] | None = None, deprecated: bool = False, security: list[SecurityRequirement] | None = None, servers: list[Server] | None = None)[source]

Describes a single API operation on a path.

class dmr.openapi.objects.ParameterMetadata(*, description: str | None = None, deprecated: bool = False, allow_empty_value: bool | None = None, style: str | None = None, explode: bool | None = None, allow_reserved: bool | None = None, example: Any | None = None, examples: dict[str, Example | Reference] | None = None)[source]

Describes metadata for a single operation parameter.

class dmr.openapi.objects.Parameter(*, description: str | None = None, deprecated: bool = False, allow_empty_value: bool | None = None, style: str | None = None, explode: bool | None = None, allow_reserved: bool | None = None, example: Any | None = None, examples: dict[str, Example | Reference] | None = None, name: str, param_in: str, schema: Schema | Reference | None = None, content: dict[str, MediaType] | None = None, required: bool = False)[source]

Bases: ParameterMetadata

Describes a single operation parameter.

class dmr.openapi.objects.PathItem(*, ref: str | None = None, summary: str | None = None, description: str | None = None, get: Operation | None = None, put: Operation | None = None, post: Operation | None = None, delete: Operation | None = None, options: Operation | None = None, head: Operation | None = None, patch: Operation | None = None, trace: Operation | None = None, servers: list[Server] | None = None, parameters: list[Parameter | Reference] | None = None)[source]

Describes the operations available on a single path.

A Path Item MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available.

dmr.openapi.objects.Paths

alias of dict[str, PathItem]

class dmr.openapi.objects.Reference(*, ref: str, summary: str | None = None, description: str | None = None)[source]

A simple object to allow referencing other components in the document.

The $ref string value contains a URI RFC3986, which identifies the location of the value being referenced.

class dmr.openapi.objects.RequestBody(*, content: dict[str, MediaType], description: str | None = None, required: bool = True)[source]

Describes a single request body.

class dmr.openapi.objects.Response(*, description: str, headers: dict[str, Header | Reference] | None = None, content: dict[str, MediaType] | None = None, links: dict[str, Link | Reference] | None = None)[source]

Describes a single response from an API Operation.

Including design-time, static links to operations based on the response.

dmr.openapi.objects.Responses

alias of dict[str, Response | Reference]

class dmr.openapi.objects.Schema(*, all_of: list[Reference | Schema] | None = None, any_of: list[Reference | Schema] | None = None, one_of: list[Reference | Schema] | None = None, schema_not: Reference | Schema | None = None, schema_if: Reference | Schema | None = None, then: Reference | Schema | None = None, schema_else: Reference | Schema | None = None, dependent_schemas: dict[str, Reference | Schema] | None=None, prefix_items: list[Reference | Schema] | None = None, items: Reference | Schema | bool | None = None, contains: Reference | Schema | None = None, properties: dict[str, Reference | Schema] | None=None, pattern_properties: dict[str, Reference | Schema] | None=None, additional_properties: Reference | Schema | bool | None = None, property_names: Reference | Schema | None = None, unevaluated_items: Reference | Schema | None = None, unevaluated_properties: Reference | Schema | None = None, type: OpenAPIType | list[OpenAPIType] | None = None, enum: list[Any] | None = None, const: Any | None = None, multiple_of: float | None = None, maximum: float | None = None, exclusive_maximum: float | None = None, minimum: float | None = None, exclusive_minimum: float | None = None, max_length: int | None = None, min_length: int | None = None, pattern: str | None = None, max_items: int | None = None, min_items: int | None = None, unique_items: bool | None = None, max_contains: int | None = None, min_contains: int | None = None, max_properties: int | None = None, min_properties: int | None = None, required: list[str] = <factory>, dependent_required: dict[str, list[str]] | None=None, format: OpenAPIFormat | None = None, content_encoding: str | None = None, content_media_type: str | None = None, content_schema: Reference | Schema | None = None, title: str | None = None, description: str | None = None, default: Any | None = None, deprecated: bool | None = None, read_only: bool | None = None, write_only: bool | None = None, examples: list[Any] | None = None, discriminator: Discriminator | None = None, xml: XML | None = None, external_docs: ExternalDocumentation | None = None, example: Any | None = None)[source]

The Schema Object allows the definition of input and output data types.

These types can be objects, but also primitives and arrays. Unless stated otherwise, the property definitions follow those of JSON Schema and do not add any additional semantics. Where JSON Schema indicates that behavior is defined by the application (e.g. for annotations), OAS also defers the definition of semantics to the application consuming the OpenAPI document.

dmr.openapi.objects.SecurityRequirement

alias of dict[str, list[str]]

class dmr.openapi.objects.SecurityScheme(*, type: Literal['apiKey', 'http', 'mutualTLS', 'oauth2', 'openIdConnect'], description: str | None = None, name: str | None = None, security_scheme_in: Literal['query', 'header', 'cookie'] | None = None, scheme: str | None = None, bearer_format: str | None = None, flows: OAuthFlows | None = None, open_id_connect_url: str | None = None)[source]

Defines a security scheme that can be used by the operations.

Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2’s common flows (implicit, password, client credentials and authorization code) as defined in RFC6749, and OpenID Connect Discovery. Please note that as of 2020, the implicit flow is about to be deprecated by OAuth 2.0 Security Best Current Practice. Recommended for most use cases is Authorization Code Grant flow with PKCE.

class dmr.openapi.objects.Server(*, url: str, description: str | None = None, variables: dict[str, ServerVariable] | None = None)[source]

An object representing a Server.

class dmr.openapi.objects.ServerVariable(*, default: str, enum: list[str] | None = None, description: str | None = None)[source]

An object representing a Server Variable for server URL template.

class dmr.openapi.objects.Tag(*, name: str, description: str | None = None, external_docs: ExternalDocumentation | None = None)[source]

Adds metadata to a single tag that is used by the Operation object.

It is not mandatory to have a Tag object per tag defined in the Operation object instances.

class dmr.openapi.objects.XML(*, name: str | None = None, namespace: str | None = None, prefix: str | None = None, attribute: bool = False, wrapped: bool = False)[source]

A metadata object that allows for more fine-tuned XML model definitions.

When using arrays, XML element names are not inferred (for singular/plural forms) and the name property SHOULD be used to add that information.

Core

class dmr.openapi.core.merger.ConfigMerger(context: OpenAPIContext)[source]

Merges OpenAPI configuration with generated paths and components.

This class is responsible for combining the OpenAPI configuration from the context with the generated paths and components to create a complete OpenAPI specification object.

__call__(paths: dict[str, PathItem], components: Components) OpenAPI[source]

Merge paths and components with configuration.

class dmr.openapi.core.registry.OperationIdRegistry[source]

Registry for OpenAPI operation IDs.

register(operation_id: str) None[source]

Register an operation ID in the registry.

class dmr.openapi.core.registry.SchemaRegistry[source]

Registry for Schemas.

get_reference(schema_name: str | None, annotation: Any | Empty = Empty()) Reference | None[source]

Get registered reference.

maybe_resolve_reference(reference: Reference | Schema, *, resolution_context: dict[str, Schema] | None = None) Schema[source]

Resolve reference and return a schema back.

register(schema_name: str, schema: Schema, annotation: Any | Empty = Empty()) Reference[source]

Register Schema in registry.

property schemas: dict[str, Schema]

Return schemas by name.

try_unregister(schema_name: str | None) None[source]

Try to unregister the schema by name.

class dmr.openapi.core.registry.SchemaCallback(*args, **kwargs)[source]

Callback protocol for the schema registration.

__call__(annotation: Any, origin: Any, type_args: Any, *, used_for_response: bool, skip_registration: bool) Schema | Reference | None[source]

Resolve the annotation into schema or into a reference.

Return None to fallback to the default resolution.

Generators

class dmr.openapi.generators.ComponentParserGenerator(_context: OpenAPIContext)[source]

Generator for OpenAPI Parameter objects.

__call__(operation_id: str, pattern: URLPattern, metadata: EndpointMetadata, serializer: type[BaseSerializer]) tuple[RequestBody | Reference | None, list[Parameter | Reference] | None][source]

Generate parameters from parsers.

class dmr.openapi.generators.ResponseGenerator(_context: OpenAPIContext)[source]

Generator for OpenAPI Response objects.

__call__(metadata: EndpointMetadata, serializer: type[BaseSerializer]) dict[str, Response | Reference][source]

Generate responses from response specs.

get_schema(response_spec: ResponseSpec, metadata: EndpointMetadata, serializer: type[BaseSerializer], context: OpenAPIContext, *, schema_field_name: Literal['schema', 'item_schema'] = 'schema', used_for_response: bool = True) Response[source]

Returns the OpenAPI schema for the response.

Can be customized in ResponseSpec subclasses.

class dmr.openapi.generators.SchemaGenerator(_context: OpenAPIContext)[source]

Generate OpenAPI schemas from different type annotations.

__call__(annotation: Any, serializer: type['BaseSerializer'], *, used_for_response: bool = False, skip_registration: Literal[True]) Schema[source]
__call__(annotation: Any, serializer: type['BaseSerializer'], *, used_for_response: bool = False, skip_registration: bool = False) Schema | Reference

Get schema for an annotation.

Here’s the algorithm we use:

  1. First, we try to find manually defined overrides for the annotation

  2. If nothing is found, we try to find any existing schema references

  3. Next, we try to get a model schema from a serializer. If it exists, we create an internal reference and return it. The next time it will be returned as a reference, cached.

  4. If nothing worked, we raise an error

Raises:

UnsolvableAnnotationsError – when we can’t generate an OpenAPI schema from an existing annotation.

class dmr.openapi.generators.SecuritySchemeGenerator(_context: OpenAPIContext)[source]

Generator for OpenAPI Security Schemes.

Responsible for processing authentication providers, extracting their security schemes, registering them in the context, and returning the corresponding security requirements for the operation.

__call__(auth_providers: Sequence[SyncAuth | AsyncAuth] | None, serializer: type[BaseSerializer]) list[SecurityRequirement] | None[source]

Process auth providers and generate security requirements.

Iterates over the provided authentication providers, registers their security schemes in the global registry, and collects their security usage requirements.

class dmr.openapi.generators.OperationIdGenerator(_context: OpenAPIContext)[source]

Generator for unique OpenAPI operation IDs.

The Operation ID builder is responsible for creating unique operation IDs for OpenAPI operations. It uses the explicit operation_id from endpoint metadata if available, otherwise generates one from the HTTP method and path following RFC 3986 specifications. All generated operation IDs are registered in the registry to ensure uniqueness across the OpenAPI specification.

__call__(path: str, suffix: str, metadata: EndpointMetadata, serializer: type[BaseSerializer]) str[source]

Generate a unique operation ID for an OpenAPI operation.

Uses the explicit operation_id from endpoint metadata if available, otherwise generates one from the HTTP method and path. The operation ID is registered in the registry to ensure uniqueness.

Existing views

class dmr.openapi.views.ScalarView(**kwargs)[source]

View for rendering the OpenAPI schema with Scalar.

Renders an interactive HTML page that allows exploring the OpenAPI specification using Scalar API Reference.

content_type

Content type of the rendered response. Defaults to "text/html".

Type:

ClassVar[str]

template_name

Template used to render the Scalar page.

Type:

ClassVar[str]

get(request: HttpRequest) HttpResponse[source]

Render the OpenAPI schema using Scalar template.

class dmr.openapi.views.SwaggerView(**kwargs)[source]

View for rendering the OpenAPI schema with Swagger UI.

Renders an interactive HTML page that allows exploring the OpenAPI specification using Swagger UI components.

content_type

Content type of the rendered response. Defaults to "text/html".

Type:

ClassVar[str]

template_name

Template used to render the Swagger UI page.

Type:

ClassVar[str]

get(request: HttpRequest) HttpResponse[source]

Render the OpenAPI schema using Swagger template.

class dmr.openapi.views.RedocView(**kwargs)[source]

View for rendering the OpenAPI schema with Redoc.

Renders an interactive HTML page that allows exploring the OpenAPI specification using Redoc components.

content_type

Content type of the rendered response. Defaults to "text/html".

Type:

ClassVar[str]

template_name

Template used to render the Redoc page.

Type:

ClassVar[str]

get(request: HttpRequest) HttpResponse[source]

Render the OpenAPI schema using Redoc template.

class dmr.openapi.views.StoplightView(**kwargs)[source]

View for rendering the OpenAPI schema with Stoplight.

Renders an interactive HTML page that allows exploring the OpenAPI specification using Stoplight API Reference.

content_type

Content type of the rendered response. Defaults to "text/html".

Type:

ClassVar[str]

template_name

Template used to render the Stoplight page.

Type:

ClassVar[str]

get(request: HttpRequest) HttpResponse[source]

Render the OpenAPI schema using Stoplight template.

class dmr.openapi.views.OpenAPIJsonView(**kwargs)[source]

View for returning the OpenAPI schema as JSON.

Produces a JSON representation of the OpenAPI specification that can be used by API documentation tools and client code generators.

content_type

Content type of the rendered response. Defaults to "application/json".

Type:

ClassVar[str]

get(request: HttpRequest) HttpResponse[source]

Render the OpenAPI schema as JSON response.

class dmr.openapi.views.yaml.OpenAPIYamlView(**kwargs)[source]

View for returning the OpenAPI schema as YAML.

This view mirrors OpenAPIJsonView, but renders the converted schema using pyyaml. Produces a YAML representation of the OpenAPI specification that can be used by API documentation tools and client code generators.

get(request: HttpRequest) HttpResponse[source]

Render the OpenAPI schema as YAML response.