Package overview


class drf_spectacular.utils.OpenApiExample(name: str, value: Optional[Any] = None, external_value: str = '', summary: str = '', description: str = '', request_only: bool = False, response_only: bool = False, media_type: str = 'application/json', status_codes: Optional[List[str]] = None)

Bases: drf_spectacular.utils.OpenApiSchemaBase

Helper class to document a API parameter / request body / response body with a concrete example value.

The example will be attached to the operation object where appropriate, i. e. where the given media_type, status_code and modifiers match. Example that do not match any scenario are ignored.

class drf_spectacular.utils.OpenApiParameter(name: str, type: Union[rest_framework.serializers.Serializer, Type[rest_framework.serializers.Serializer], Type[Union[str, float, bool, bytes, int, uuid.UUID, decimal.Decimal, datetime.datetime,, dict]], drf_spectacular.types.OpenApiTypes, dict] = <class 'str'>, location: str = 'query', required: bool = False, description: str = '', enum: Optional[List[Any]] = None, deprecated: bool = False, style: Optional[str] = None, explode: Optional[bool] = None, default: Optional[Any] = None, examples: Optional[List[drf_spectacular.utils.OpenApiExample]] = None, exclude: bool = False, response: Union[bool, List[Union[int, str]]] = False)

Bases: drf_spectacular.utils.OpenApiSchemaBase

Helper class to document request query/path/header/cookie parameters. Can also be used to document response headers.

Please note that not all arguments apply to all location/type/direction variations, e.g. path parameters are required=True by definition.

For valid style choices please consult the OpenAPI specification.

COOKIE = 'cookie'
HEADER = 'header'
PATH = 'path'
QUERY = 'query'
class drf_spectacular.utils.OpenApiResponse(response: Optional[Any] = None, description: Optional[str] = None, examples: Optional[List[drf_spectacular.utils.OpenApiExample]] = None)

Bases: drf_spectacular.utils.OpenApiSchemaBase

Helper class to bundle a response object (Serializer, OpenApiType, raw schema, etc) together with a response object description and/or examples. Examples can alternatively be provided via @extend_schema.

This class is especially helpful for explicitly describing status codes on a “Response Object” level.

class drf_spectacular.utils.OpenApiSchemaBase

Bases: object

class drf_spectacular.utils.PolymorphicProxySerializer(*args, **kwargs)

Bases: rest_framework.serializers.Serializer

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:

            LegalPersonSerializer, NaturalPersonSerializer,
def create(self, request, *args, **kwargs):
    return Response(...)

Beware that this is not a real serializer and it will raise an AssertionError if used in that way. It cannot be used in views as serializer_class or as field in an actual serializer. It is solely meant for annotation purposes.

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. Setting resource_type_field_name to None will remove the discriminator altogether. This may be useful in certain situations, but will most likely break client generation.

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.

property data

Dict of native values <- Dict of primitive datatypes.


Object instance -> Dict of primitive datatypes.

drf_spectacular.utils.extend_schema(operation_id: Optional[str] = None, parameters: Optional[List[Union[drf_spectacular.utils.OpenApiParameter, rest_framework.serializers.Serializer, Type[rest_framework.serializers.Serializer]]]] = None, request: Any = <class 'rest_framework.fields.empty'>, responses: Any = <class 'rest_framework.fields.empty'>, auth: Optional[List[str]] = None, description: Optional[str] = None, summary: Optional[str] = None, deprecated: Optional[bool] = None, tags: Optional[List[str]] = None, exclude: bool = False, operation: Optional[Dict] = None, methods: Optional[List[str]] = None, versions: Optional[List[str]] = None, examples: Optional[List[drf_spectacular.utils.OpenApiExample]] = None) Callable[[drf_spectacular.utils.F], drf_spectacular.utils.F]

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

  • 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.

    • dict with tuple (status_code, media_type) as keys and Serializers as values.

    • basic types or instances of OpenApiTypes

    • OpenApiResponse for bundling any of the other choices together with either a dedicated response description and/or examples.

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

  • request

    replaces the discovered Serializer. Takes a variety of inputs

    • Serializer class/instance

    • basic types or instances of OpenApiTypes

    • PolymorphicProxySerializer for signaling that the operation accepts a set of different types of objects.

    • dict with media_type as keys and one of the above as values.

  • auth – replace discovered auth with explicit list of auth methods

  • 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.

  • examples – attach request/response examples to the operation


drf_spectacular.utils.extend_schema_field(field: Union[rest_framework.serializers.Serializer, Type[rest_framework.serializers.Serializer], rest_framework.fields.Field, drf_spectacular.types.OpenApiTypes, Dict], component_name: Optional[str] = None) Callable[[drf_spectacular.utils.F], drf_spectacular.utils.F]

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).

  • field – accepts a Serializer, OpenApiTypes or raw dict

  • component_name – signals that the field should be broken out as separate component

drf_spectacular.utils.extend_schema_serializer(many: Optional[bool] = None, exclude_fields: Optional[List[str]] = None, deprecate_fields: Optional[List[str]] = None, examples: Optional[List[drf_spectacular.utils.OpenApiExample]] = None) Callable[[drf_spectacular.utils.F], drf_spectacular.utils.F]

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

  • 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.

  • deprecate_fields – fields to mark as deprecated while processing the serializer.

  • examples – define example data to serializer.

drf_spectacular.utils.extend_schema_view(**kwargs) Callable[[drf_spectacular.utils.F], drf_spectacular.utils.F]

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.

This decorator also takes care of safely attaching annotations to derived view methods, preventing leakage into unrelated views.


kwargs – method names as argument names and @extend_schema calls as values

drf_spectacular.utils.inline_serializer(name: str, fields: Dict[str, rest_framework.fields.Field], **kwargs) 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.

  • name – name of the

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

  • kwargs – optional kwargs for serializer initialization


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)

ANY = 25
BOOL = 4
BYTE = 6
DATE = 19
EMAIL = 22
INT = 9
INT32 = 10
INT64 = 11
IP4 = 14
IP6 = 15
NONE = 24
STR = 5
TIME = 20
URI = 13
UUID = 12


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
authentication_classes = [<class 'rest_framework.authentication.SessionAuthentication'>, <class 'rest_framework.authentication.BasicAuthentication'>]

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

authentication_classes = [<class 'rest_framework.authentication.SessionAuthentication'>, <class 'rest_framework.authentication.BasicAuthentication'>]
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.SpectacularSwaggerSplitView(**kwargs)

Bases: drf_spectacular.views.SpectacularSwaggerView

Alternate Swagger UI implementation that separates the html request from the javascript request to cater to web servers with stricter CSP policies.

get(request, *args, **kwargs)
url_self = None
class drf_spectacular.views.SpectacularSwaggerView(**kwargs)

Bases: rest_framework.views.APIView

authentication_classes = [<class 'rest_framework.authentication.SessionAuthentication'>, <class 'rest_framework.authentication.BasicAuthentication'>]
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'>]


class drf_spectacular.extensions.OpenApiAuthenticationExtension(target)


Extension for specifying authentication schemes.

The view class is available via auto_schema.view, while the original authentication class can be accessed via If you want to override an included extension, be sure to set a higher matching priority by setting the class attribute priority = 1 or higher.

get_security_definition() is expected to return a valid OpenAPI security scheme object

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


Extension for specifying a list of filter parameters for a given FilterBackend.

The original filter class object can be accessed via The attached view is accessible via auto_schema.view.

get_schema_operation_parameters() is expected to return either an empty list or a list of valid OpenAPI parameter objects.

abstract get_schema_operation_parameters(auto_schema: AutoSchema, *args, **kwargs) List[dict]
class drf_spectacular.extensions.OpenApiSerializerExtension(target)


Extension for replacing an insufficient or specifying an unknown Serializer schema.

The existing implementation of map_serializer() will generate the same result as drf-spectacular would. Either augment or replace the generated schema. The view instance is available via auto_schema.view, while the original serializer can be accessed via

map_serializer() is expected to return a valid OpenAPI schema object.

get_name() Optional[str]

return str for overriding default name extraction

map_serializer(auto_schema: AutoSchema, direction)

override for customized serializer mapping

class drf_spectacular.extensions.OpenApiSerializerFieldExtension(target)


Extension for replacing an insufficient or specifying an unknown SerializerField schema.

To augment the default schema, you can get what drf-spectacular would generate with auto_schema._map_serializer_field(, direction, bypass_extensions=True). and edit the returned schema at your discretion. Beware that this may still emit warnings, in which case manual construction is advisable.

map_serializer_field() is expected to return a valid OpenAPI schema object.

get_name() Optional[str]

return str for breaking out field schema into separate named component

abstract map_serializer_field(auto_schema: AutoSchema, direction)

override for customized serializer field mapping

class drf_spectacular.extensions.OpenApiViewExtension(target)


Extension for replacing discovered views with a more schema-appropriate/annotated version.

view_replacement() is expected to return a subclass of APIView (which includes ViewSet et al.). The discovered original view instance can be accessed with and be subclassed if desired.

abstract view_replacement() Type[APIView]


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.


class drf_spectacular.openapi.AutoSchema

Bases: rest_framework.schemas.inspectors.ViewInspector


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.


override this for custom behaviour

get_operation(path, path_regex, path_prefix, method, registry:

override this for custom behaviour


override this for custom behaviour

get_request_serializer() Any

override this for custom behaviour

get_response_serializers() Any

override this for custom behaviour


override this for custom behaviour

get_tags() List[str]

override this for custom behaviour


override this for custom behaviour

method_mapping = {'delete': 'destroy', 'get': 'retrieve', 'patch': 'partial_update', 'post': 'create', 'put': 'update'}
resolve_serializer(serializer, direction)


class drf_spectacular.contrib.django_filters.DjangoFilterExtension(target)


Extensions that specifically deals with django-filter fields. The introspection attempts to estimate the underlying model field types to generate filter types.

However, there are under-specified filter fields for which heuristics need to be performed. This serves as an explicit list of all partially-handled filter fields:

  • AllValuesFilter: skip choices to prevent DB query

  • AllValuesMultipleFilter: skip choices to prevent DB query, multi handled though

  • ChoiceFilter: enum handled, type under-specified

  • DateRangeFilter: N/A

  • LookupChoiceFilter: N/A

  • ModelChoiceFilter: enum handled

  • ModelMultipleChoiceFilter: enum, multi handled

  • MultipleChoiceFilter: enum, multi handled

  • RangeFilter: min/max handled, type under-specified

  • TypedChoiceFilter: enum handled

  • TypedMultipleChoiceFilter: enum, multi handled

In case of warnings or incorrect filter types, you can manually override the underlying field type with a manual extend_schema_field decoration.

class SomeFilter(FilterSet):
    some_field = extend_schema_field(OpenApiTypes.NUMBER)(