Package overview

drf_spectacular.utils

class drf_spectacular.utils.OpenApiParameter(name, type=<class 'str'>, location='query', required=False, description='', enum=None, deprecated=False)

Bases: drf_spectacular.utils.OpenApiSchemaBase

COOKIE = 'cookie'
HEADER = 'header'
PATH = 'path'
QUERY = 'query'
class drf_spectacular.utils.OpenApiSchemaBase

Bases: object

class drf_spectacular.utils.PolymorphicProxySerializer(component_name: str, serializers: Union[List[Union[rest_framework.serializers.Serializer, Type[rest_framework.serializers.Serializer]]], Dict[str, Union[rest_framework.serializers.Serializer, Type[rest_framework.serializers.Serializer]]]], resource_type_field_name: str)

Bases: object

This class is to be used with @extend_schema to signal a request/response might be polymorphic (accepts/returns data possibly from different serializers). Usage usually looks like this:

@extend_schema(
    request=PolymorphicProxySerializer(
        component_name='MetaPerson',
        serializers=[
            LegalPersonSerializer, NaturalPersonSerializer,
        ],
        resource_type_field_name='person_type',
    )
)
def create(self, request, *args, **kwargs):
    return Response(...)

Beware that this is not a real serializer and therefore is not derived from serializers.Serializer. It cannot be used in views as serializer_class or as field in a actual serializer. You likely want to handle this in the view method.

Also make sure that each sub-serializer has a field named after the value of resource_type_field_name (discriminator field). Generated clients will likely depend on the existence of this field.

For that reason, it is strongly recommended to pass the Serializers as list, and by that let drf-spectacular retrieve the field and handle the mapping automatically. In special circumstances, the field may not available when drf-spectacular processes the serializer. In those cases you can explicitly state the mapping with {'legal': LegalPersonSerializer, ...}, but it is then your responsibility to have a valid mapping.

drf_spectacular.utils.extend_schema(operation_id=None, parameters=None, request=<class 'rest_framework.fields.empty'>, responses=<class 'rest_framework.fields.empty'>, auth=None, description=None, summary=None, deprecated=None, tags=None, exclude=False, operation=None, methods=None, versions=None)

decorator mainly for the “view” method kind. partially or completely overrides what would be generated by drf-spectacular.

Parameters
  • operation_id – replaces the auto-generated operation_id. make sure there are no naming collisions.

  • parameters – list of additional or replacement parameters added to the auto-discovered fields.

  • responses

    replaces the discovered Serializer. Takes a variety of inputs that can be used individually or combined

    • Serializer class

    • Serializer instance (e.g. Serializer(many=True) for listings)

    • dict with status codes as keys and Serializers as values.

    • PolymorphicProxySerializer for signaling that the operation may yield data from different serializers depending on the circumstances.

  • request – replaces the discovered Serializer.

  • auth

  • description – replaces discovered doc strings

  • summary – an optional short summary of the description

  • deprecated – mark operation as deprecated

  • tags – override default list of tags

  • exclude – set True to exclude operation from schema

  • operation – manually override what auto-discovery would generate. you must provide a OpenAPI3-compliant dictionary that gets directly translated to YAML.

  • methods – scope extend_schema to specific methods. matches all by default.

  • versions – scope extend_schema to specific API version. matches all by default.

Returns

drf_spectacular.utils.extend_schema_field(field)

Decorator for the “field” kind. Can be used with SerializerMethodField (annotate the actual method) or with custom serializers.Field implementations.

If your custom serializer field base class is already the desired type, decoration is not necessary. To override the discovered base class type, you can decorate your custom field class.

Always takes precedence over other mechanisms (e.g. type hints, auto-discovery).

Parameters

field – accepts a Serializer or OpenApiTypes

drf_spectacular.utils.extend_schema_serializer(many=None, exclude_fields=None)

Decorator for the “serializer” kind. Intended for overriding default serializer behaviour that cannot be influenced through .extend_schema.

Parameters
  • many – override how serializer is initialized. Mainly used to coerce the list view detection heuristic to acknowledge a non-list serializer.

  • exclude_fields – fields to ignore while processing the serializer. only affects the schema. fields will still be exposed through the API.

drf_spectacular.utils.extend_schema_view(**kwargs)

Convenience decorator for the “view” kind. Intended for annotating derived view methods that are are not directly present in the view (usually methods like list or retrieve). Spares you from overriding methods like list, only to perform a super call in the body so that you have have something to attach @extend_schema to.

Parameters

kwargs – method names as argument names and extend_schema() calls as values

drf_spectacular.utils.inline_serializer(name: str, fields: Dict[str, object], **kwargs) → Union[rest_framework.serializers.Serializer, Type[rest_framework.serializers.Serializer]]

A helper function to create an inline serializer. Primary use is with @extend_schema, where one needs an implicit one-off serializer that is not reflected in an actual class.

Parameters
  • name – name of the

  • fields – dict with field names as keys and serializer fields as values

  • kwargs – optional kwargs for serializer initialization

drf_spectacular.types

class drf_spectacular.types.OpenApiTypes(value)

Basic types known to the OpenApi specification or at least common format extension of it.

  • Use BYTE for base64 encoded data wrapped in a string

  • Use BINARY for raw binary data

  • Use OBJECT for arbitrary free-form object (usually a dict)

BINARY = 5
BOOL = 2
BYTE = 4
DATE = 15
DATETIME = 14
DECIMAL = 13
EMAIL = 17
FLOAT = 1
HOSTNAME = 12
INT = 7
IP4 = 10
IP6 = 11
NONE = 19
OBJECT = 18
PASSWORD = 6
STR = 3
TIME = 16
URI = 9
UUID = 8

drf_spectacular.views

class drf_spectacular.views.SpectacularAPIView(**kwargs)

Bases: rest_framework.views.APIView

OpenApi3 schema for this API. Format can be selected via content negotiation.

  • YAML: application/vnd.oai.openapi

  • JSON: application/vnd.oai.openapi+json

api_version = None
generator_class

alias of drf_spectacular.generators.SchemaGenerator

get(request, *args, **kwargs)
permission_classes = [<class 'rest_framework.permissions.AllowAny'>]
renderer_classes = [<class 'drf_spectacular.renderers.OpenApiYamlRenderer'>, <class 'drf_spectacular.renderers.OpenApiYamlRenderer2'>, <class 'drf_spectacular.renderers.OpenApiJsonRenderer'>, <class 'drf_spectacular.renderers.OpenApiJsonRenderer2'>]
serve_public = True
urlconf = None
class drf_spectacular.views.SpectacularJSONAPIView(**kwargs)

Bases: drf_spectacular.views.SpectacularAPIView

renderer_classes = [<class 'drf_spectacular.renderers.OpenApiJsonRenderer'>, <class 'drf_spectacular.renderers.OpenApiJsonRenderer2'>]
class drf_spectacular.views.SpectacularRedocView(**kwargs)

Bases: rest_framework.views.APIView

get(request, *args, **kwargs)
permission_classes = [<class 'rest_framework.permissions.AllowAny'>]
renderer_classes = [<class 'rest_framework.renderers.TemplateHTMLRenderer'>]
template_name = 'drf_spectacular/redoc.html'
url = None
url_name = 'schema'
class drf_spectacular.views.SpectacularSwaggerView(**kwargs)

Bases: rest_framework.views.APIView

get(request, *args, **kwargs)
permission_classes = [<class 'rest_framework.permissions.AllowAny'>]
renderer_classes = [<class 'rest_framework.renderers.TemplateHTMLRenderer'>]
template_name = 'drf_spectacular/swagger_ui.html'
template_name_js = 'drf_spectacular/swagger_ui.js'
url = None
url_name = 'schema'
class drf_spectacular.views.SpectacularYAMLAPIView(**kwargs)

Bases: drf_spectacular.views.SpectacularAPIView

renderer_classes = [<class 'drf_spectacular.renderers.OpenApiYamlRenderer'>, <class 'drf_spectacular.renderers.OpenApiYamlRenderer2'>]

drf_spectacular.extensions

class drf_spectacular.extensions.OpenApiAuthenticationExtension(target)

Bases: drf_spectacular.plumbing.OpenApiGeneratorExtension

abstract get_security_definition(auto_schema)
get_security_requirement(auto_schema)
name: str
class drf_spectacular.extensions.OpenApiSerializerExtension(target)

Bases: drf_spectacular.plumbing.OpenApiGeneratorExtension

get_name() → Optional[str]

return str for overriding default name extraction

map_serializer(auto_schema, direction)

override for customized serializer mapping

class drf_spectacular.extensions.OpenApiSerializerFieldExtension(target)

Bases: drf_spectacular.plumbing.OpenApiGeneratorExtension

abstract map_serializer_field(auto_schema, direction)
class drf_spectacular.extensions.OpenApiViewExtension(target)

Bases: drf_spectacular.plumbing.OpenApiGeneratorExtension

abstract view_replacement()

drf_spectacular.hooks

drf_spectacular.hooks.postprocess_schema_enums(result, generator, **kwargs)

simple replacement of Enum/Choices that globally share the same name and have the same choices. Aids client generation to not generate a separate enum for every occurrence. only takes effect when replacement is guaranteed to be correct.

drf_spectacular.hooks.preprocess_exclude_path_format(endpoints, **kwargs)

preprocessing hook that filters out {format} suffixed paths, in case format_suffix_patterns is used and {format} path params are unwanted.

drf_spectacular.openapi

class drf_spectacular.openapi.AutoSchema

Bases: rest_framework.schemas.inspectors.ViewInspector

get_auth()

Obtains authentication classes and permissions from view. If authentication is known, resolve security requirement for endpoint and security definition for the component section. For custom authentication subclass OpenApiAuthenticationExtension.

get_description()

override this for custom behaviour

get_operation(path, path_regex, method, registry: drf_spectacular.plumbing.ComponentRegistry)
get_operation_id()

override this for custom behaviour

get_override_parameters()

override this for custom behaviour

get_request_serializer()

override this for custom behaviour

get_response_serializers()

override this for custom behaviour

get_summary()

override this for custom behaviour

get_tags() → List[str]

override this for custom behaviour

is_deprecated()

override this for custom behaviour

map_parsers()
map_renderers(attribute)
method_mapping = {'delete': 'destroy', 'get': 'retrieve', 'patch': 'partial_update', 'post': 'create', 'put': 'update'}
resolve_serializer(serializer, direction) → drf_spectacular.plumbing.ResolvedComponent