drf_yasg package

drf_yasg.codecs

drf_yasg.codecs._validate_flex(spec)[source]
drf_yasg.codecs._validate_swagger_spec_validator(spec)[source]
drf_yasg.codecs.VALIDATORS = {'flex': <function _validate_flex>, 'ssv': <function _validate_swagger_spec_validator>}
class drf_yasg.codecs._OpenAPICodec(validators)[source]

Bases: object

media_type = None
validators

List of validator names to apply

encode(document)[source]

Transform an Swagger object to a sequence of bytes.

Also performs validation and applies settings.

Parameters:document (openapi.Swagger) – Swagger spec object as generated by OpenAPISchemaGenerator
Returns:binary encoding of document
Return type:bytes
encode_error(err)[source]

Dump an error message into an encoding-appropriate sequence of bytes

_dump_dict(spec)[source]

Dump the given dictionary into its string representation.

Parameters:spec (dict) – a python dict
Returns:string representation of spec
Return type:str or bytes
generate_swagger_object(swagger)[source]

Generates the root Swagger object.

Parameters:swagger (openapi.Swagger) – Swagger spec object as generated by OpenAPISchemaGenerator
Returns:swagger spec as dict
Return type:OrderedDict
class drf_yasg.codecs.OpenAPICodecJson(validators, pretty=False, media_type='application/json')[source]

Bases: drf_yasg.codecs._OpenAPICodec

media_type = 'application/json'
_dump_dict(spec)[source]

Dump spec into JSON.

Return type:str
drf_yasg.codecs.yaml_sane_dump(data, binary)[source]

Dump the given data dictionary into a sane format:

  • OrderedDicts are dumped as regular mappings instead of non-standard !!odict
  • multi-line mapping style instead of json-like inline style
  • list elements are indented into their parents
  • YAML references/aliases are disabled
Parameters:
  • data (dict) – the data to be dumped
  • binary (bool) – True to return a utf-8 encoded binary object, False to return a string
Returns:

the serialized YAML

Return type:

str or bytes

drf_yasg.codecs.yaml_sane_load(stream)[source]

Load the given YAML stream while preserving the input order for mapping items.

Parameters:stream – YAML stream (can be a string or a file-like object)
Return type:OrderedDict
class drf_yasg.codecs.OpenAPICodecYaml(validators, media_type='application/yaml')[source]

Bases: drf_yasg.codecs._OpenAPICodec

media_type = 'application/yaml'
_dump_dict(spec)[source]

Dump spec into YAML.

Return type:bytes

drf_yasg.errors

exception drf_yasg.errors.SwaggerError[source]

Bases: Exception

exception drf_yasg.errors.SwaggerValidationError(msg, errors=None, spec=None, source_codec=None, *args)[source]

Bases: drf_yasg.errors.SwaggerError

exception drf_yasg.errors.SwaggerGenerationError[source]

Bases: drf_yasg.errors.SwaggerError

drf_yasg.generators

class drf_yasg.generators.EndpointEnumerator(patterns=None, urlconf=None, request=None)[source]

Bases: rest_framework.schemas.generators.EndpointEnumerator

get_path_from_regex(path_regex)[source]

Given a URL conf regex, return a URI template string.

should_include_endpoint(path, callback, app_name='', namespace='', url_name=None)[source]

Return True if the given endpoint should be included.

replace_version(path, callback)[source]

If request.version is not None and callback uses URLPathVersioning, this function replaces the version parameter in path with the actual version.

Parameters:
  • path (str) – the templated path
  • callback – the view callback
Return type:

str

get_api_endpoints(patterns=None, prefix='', app_name=None, namespace=None, ignored_endpoints=None)[source]

Return a list of all available API endpoints by inspecting the URL conf.

Copied entirely from super.

unescape(s)[source]

Unescape all backslash escapes from s.

Parameters:s (str) – string with backslash escapes
Return type:str
unescape_path(path)[source]

Remove backslashe escapes from all path components outside {parameters}. This is needed because simplify_regex does not handle this correctly.

NOTE: this might destructively affect some url regex patterns that contain metacharacters (e.g. w, d) outside path parameter groups; if you are in this category, God help you

Parameters:path (str) – path possibly containing
Returns:the unescaped path
Return type:str
class drf_yasg.generators.OpenAPISchemaGenerator(info, version='', url=None, patterns=None, urlconf=None)[source]

Bases: object

This class iterates over all registered API endpoints and returns an appropriate OpenAPI 2.0 compliant schema. Method implementations shamelessly stolen and adapted from rest-framework SchemaGenerator.

Parameters:
  • info (openapi.Info) – information about the API
  • version (str) – API version string; if omitted, info.default_version will be used
  • url (str) –

    API scheme, host and port; if None is passed and DEFAULT_API_URL is not set, the url will be inferred from the request made against the schema view, so you should generally not need to set this parameter explicitly; if the empty string is passed, no host and scheme will be emitted

    If url is not None or the empty string, it must be a scheme-absolute uri (i.e. starting with http:// or https://), and any path component is ignored;

    See also: documentation on base URL construction

  • patterns – if given, only these patterns will be enumerated for inclusion in the API spec
  • urlconf – if patterns is not given, use this urlconf to enumerate patterns; if not given, the default urlconf is used
endpoint_enumerator_class

alias of EndpointEnumerator

url
get_security_definitions()[source]

Get the security schemes for this API. This determines what is usable in security requirements, and helps clients configure their authorization credentials.

Returns:the security schemes usable with this API
Return type:dict[str,dict] or None
get_security_requirements(security_definitions)[source]

Get the base (global) security requirements of the API. This is never called if get_security_definitions() returns None.

Parameters:security_definitions – security definitions as returned by get_security_definitions()
Returns:the security schemes accepted by default
Return type:list[dict[str,list[str]]] or None
get_schema(request=None, public=False)[source]

Generate a Swagger object representing the API schema.

Parameters:
  • request (rest_framework.request.Request or None) – the request used for filtering accessible endpoints and finding the spec URI
  • public (bool) – if True, all endpoints are included regardless of access through request
Returns:

the generated Swagger specification

Return type:

openapi.Swagger

create_view(callback, method, request=None)[source]

Create a view instance from a view callback as registered in urlpatterns.

Parameters:
  • callback – view callback registered in urlpatterns
  • method (str) – HTTP method
  • request (rest_framework.request.Request or None) – request to bind to the view
Returns:

the view instance

coerce_path(path, view)[source]

Coerce {pk} path arguments into the name of the model field, where possible. This is cleaner for an external representation (i.e. “this is an identifier”, not “this is a database primary key”).

Parameters:
  • path (str) – the path
  • view (rest_framework.views.APIView) – associated view
Return type:

str

get_endpoints(request)[source]

Iterate over all the registered endpoints in the API and return a fake view with the right parameters.

Parameters:request (rest_framework.request.Request or None) – request to bind to the endpoint views
Returns:{path: (view_class, list[(http_method, view_instance)])
Return type:dict[str,(type,list[(str,rest_framework.views.APIView)])]
get_operation_keys(subpath, method, view)[source]

Return a list of keys that should be used to group an operation within the specification.

/users/                   ("users", "list"), ("users", "create")
/users/{pk}/              ("users", "read"), ("users", "update"), ("users", "delete")
/users/enabled/           ("users", "enabled")  # custom viewset list action
/users/{pk}/star/         ("users", "star")     # custom viewset detail action
/users/{pk}/groups/       ("users", "groups", "list"), ("users", "groups", "create")
/users/{pk}/groups/{pk}/  ("users", "groups", "read"), ("users", "groups", "update")
Parameters:
  • subpath (str) – path to the operation with any common prefix/base path removed
  • method (str) – HTTP method
  • view – the view associated with the operation
Return type:

list[str]

determine_path_prefix(paths)[source]

Given a list of all paths, return the common prefix which should be discounted when generating a schema structure.

This will be the longest common string that does not include that last component of the URL, or the last component before a path parameter.

For example:

/api/v1/users/
/api/v1/users/{pk}/

The path prefix is /api/v1/.

Parameters:paths (list[str]) – list of paths
Return type:str
should_include_endpoint(path, method, view, public)[source]

Check if a given endpoint should be included in the resulting schema.

Parameters:
  • path (str) – request path
  • method (str) – http request method
  • view – instantiated view callback
  • public (bool) – if True, all endpoints are included regardless of access through request
Returns:

true if the view should be excluded

Return type:

bool

get_paths_object(paths)[source]

Construct the Swagger Paths object.

Parameters:paths (OrderedDict[str,openapi.PathItem]) – mapping of paths to PathItem objects
Returns:the Paths object
Return type:openapi.Paths
get_paths(endpoints, components, request, public)[source]

Generate the Swagger Paths for the API from the given endpoints.

Parameters:
  • endpoints (dict) – endpoints as returned by get_endpoints
  • components (ReferenceResolver) – resolver/container for Swagger References
  • request (Request) – the request made against the schema view; can be None
  • public (bool) – if True, all endpoints are included regardless of access through request
Returns:

the Paths object and the longest common path prefix, as a 2-tuple

Return type:

tuple[openapi.Paths,str]

get_operation(view, path, prefix, method, components, request)[source]

Get an Operation for the given API endpoint (path, method). This method delegates to get_operation() of a ViewInspector determined according to settings and @swagger_auto_schema overrides.

Parameters:
  • view – the view associated with this endpoint
  • path (str) – the path component of the operation URL
  • prefix (str) – common path prefix among all endpoints
  • method (str) – the http method of the operation
  • components (openapi.ReferenceResolver) – referenceable components
  • request (Request) – the request made against the schema view; can be None
Return type:

openapi.Operation

get_path_item(path, view_cls, operations)[source]

Get a PathItem object that describes the parameters and operations related to a single path in the API.

Parameters:
  • path (str) – the path
  • view_cls (type) – the view that was bound to this path in urlpatterns
  • operations (dict[str,openapi.Operation]) – operations defined on this path, keyed by lowercase HTTP method
Return type:

openapi.PathItem

get_overrides(view, method)[source]

Get overrides specified for a given operation.

Parameters:
  • view – the view associated with the operation
  • method (str) – HTTP method
Returns:

a dictionary containing any overrides set by @swagger_auto_schema

Return type:

dict

get_path_parameters(path, view_cls)[source]

Return a list of Parameter instances corresponding to any templated path variables.

Parameters:
  • path (str) – templated request path
  • view_cls (type) – the view class associated with the path
Returns:

path parameters

Return type:

list[openapi.Parameter]

drf_yasg.inspectors

drf_yasg.inspectors.NotHandled = <object object>

The most base type

class drf_yasg.inspectors.BaseInspector(view, path, method, components, request)

Bases: object

Parameters:
  • view (rest_framework.views.APIView) – the view associated with this endpoint
  • path (str) – the path component of the operation URL
  • method (str) – the http method of the operation
  • components (openapi.ReferenceResolver) – referenceable components
  • request (rest_framework.request.Request) – the request made against the schema view; can be None
get_parser_classes()[source]

Get the parser classes of this view by calling get_parsers.

Returns:parser classes
Return type:list[type[rest_framework.parsers.BaseParser]]
get_renderer_classes()[source]

Get the renderer classes of this view by calling get_renderers.

Returns:renderer classes
Return type:list[type[rest_framework.renderers.BaseRenderer]]
probe_inspectors(inspectors, method_name, obj, initkwargs=None, **kwargs)[source]

Probe a list of inspectors with a given object. The first inspector in the list to return a value that is not NotHandled wins.

Parameters:
  • inspectors (list[type[BaseInspector]]) – list of inspectors to probe
  • method_name (str) – name of the target method on the inspector
  • obj – first argument to inspector method
  • initkwargs (dict) – extra kwargs for instantiating inspector class
  • kwargs – additional arguments to inspector method
Returns:

the return value of the winning inspector, or None if no inspector handled the object

process_result(result, method_name, obj, **kwargs)[source]

After an inspector handles an object (i.e. returns a value other than NotHandled), all inspectors that were probed get the chance to alter the result, in reverse order. The inspector that handled the object is the first to receive a process_result call with the object it just returned.

This behaviour is similar to the Django request/response middleware processing.

If this inspector has no post-processing to do, it should just return result (the default implementation).

Parameters:
  • result – the return value of the winning inspector, or None if no inspector handled the object
  • method_name (str) – name of the method that was called on the inspector
  • obj – first argument passed to inspector method
  • kwargs – additional arguments passed to inspector method
Returns:

class drf_yasg.inspectors.FilterInspector(view, path, method, components, request)

Bases: drf_yasg.inspectors.BaseInspector

Base inspector for filter backends.

Responsible for determining extra query parameters added by given filter backends.

Parameters:
  • view (rest_framework.views.APIView) – the view associated with this endpoint
  • path (str) – the path component of the operation URL
  • method (str) – the http method of the operation
  • components (openapi.ReferenceResolver) – referenceable components
  • request (rest_framework.request.Request) – the request made against the schema view; can be None
get_filter_parameters(filter_backend)[source]

Get the filter parameters for a single filter backend instance.

Should return NotHandled if this inspector does not know how to handle the given filter_backend.

Parameters:filter_backend (BaseFilterBackend) – the filter backend
Return type:list[openapi.Parameter]
class drf_yasg.inspectors.PaginatorInspector(view, path, method, components, request)

Bases: drf_yasg.inspectors.BaseInspector

Base inspector for paginators.

Responisble for determining extra query parameters and response structure added by given paginators.

Parameters:
  • view (rest_framework.views.APIView) – the view associated with this endpoint
  • path (str) – the path component of the operation URL
  • method (str) – the http method of the operation
  • components (openapi.ReferenceResolver) – referenceable components
  • request (rest_framework.request.Request) – the request made against the schema view; can be None
get_paginated_response(paginator, response_schema)[source]

Add appropriate paging fields to a response Schema.

Should return NotHandled if this inspector does not know how to handle the given paginator.

Parameters:
  • paginator (BasePagination) – the paginator
  • response_schema (openapi.Schema) – the response schema that must be paged.
Return type:

openapi.Schema

get_paginator_parameters(paginator)[source]

Get the pagination parameters for a single paginator instance.

Should return NotHandled if this inspector does not know how to handle the given paginator.

Parameters:paginator (BasePagination) – the paginator
Return type:list[openapi.Parameter]
class drf_yasg.inspectors.FieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.BaseInspector

Base inspector for serializers and serializer fields.

_get_partial_types(field, swagger_object_type, use_references, **kwargs)[source]

Helper method to extract generic information from a field and return a partial constructor for the appropriate openapi object.

All arguments are the same as field_to_swagger_object().

The return value is a tuple consisting of:

  • a function for constructing objects of swagger_object_type; its prototype is:

    def SwaggerType(existing_object=None, **instance_kwargs):
    

    This function creates an instance of swagger_object_type, passing the following attributes to its init, in order of precedence:

    • arguments specified by the kwargs parameter of _get_partial_types()
    • instance_kwargs passed to the constructor function
    • title, description, required, x-nullable and default inferred from the field, where appropriate

    If existing_object is not None, it is updated instead of creating a new object.

  • a type that should be used for child objects if field is of an array type. This can currently have two values:

Return type:(function,type[openapi.Schema] or type[openapi.Items])
add_manual_fields(serializer_or_field, schema)[source]

Set fields from the swagger_schem_fields attribute on the Meta class. This method is called only for serializers or fields that are converted into openapi.Schema objects.

Parameters:
  • serializer_or_field – serializer or field instance
  • schema (openapi.Schema) – the schema object to be modified in-place
field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

probe_field_inspectors(field, swagger_object_type, use_references, **kwargs)[source]

Helper method for recursively probing field_inspectors to handle a given field.

All arguments are the same as field_to_swagger_object().

Return type:openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef
class drf_yasg.inspectors.SerializerInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

get_request_parameters(serializer, in_)[source]

Convert a DRF serializer into a list of Parameters.

Should return NotHandled if this inspector does not know how to handle the given serializer.

Parameters:
  • serializer (serializers.BaseSerializer) – the Serializer instance
  • in (str) – the location of the parameters, one of the openapi.IN_* constants
Return type:

list[openapi.Parameter]

get_schema(serializer)[source]

Convert a DRF Serializer instance to an openapi.Schema.

Should return NotHandled if this inspector does not know how to handle the given serializer.

Parameters:serializer (serializers.BaseSerializer) – the Serializer instance
Return type:openapi.Schema
class drf_yasg.inspectors.ViewInspector(view, path, method, components, request, overrides)

Bases: drf_yasg.inspectors.BaseInspector

Inspector class responsible for providing Operation definitions given a view, path and method.

Parameters:overrides (dict) – manual overrides as passed to @swagger_auto_schema
_prepend_inspector_overrides(inspectors)[source]
body_methods = ('PUT', 'PATCH', 'POST', 'DELETE')
field_inspectors = [<class 'drf_yasg.inspectors.field.CamelCaseJSONFilter'>, <class 'drf_yasg.inspectors.field.RecursiveFieldInspector'>, <class 'drf_yasg.inspectors.field.ReferencingSerializerInspector'>, <class 'drf_yasg.inspectors.field.ChoiceFieldInspector'>, <class 'drf_yasg.inspectors.field.FileFieldInspector'>, <class 'drf_yasg.inspectors.field.DictFieldInspector'>, <class 'drf_yasg.inspectors.field.HiddenFieldInspector'>, <class 'drf_yasg.inspectors.field.RelatedFieldInspector'>, <class 'drf_yasg.inspectors.field.SerializerMethodFieldInspector'>, <class 'drf_yasg.inspectors.field.SimpleFieldInspector'>, <class 'drf_yasg.inspectors.field.StringDefaultFieldInspector'>]
filter_inspectors = [<class 'drf_yasg.inspectors.query.CoreAPICompatInspector'>]
get_filter_parameters()[source]

Return the parameters added to the view by its filter backends.

Return type:list[openapi.Parameter]
get_operation(operation_keys)[source]

Get an Operation for the given API endpoint (path, method). This includes query, body parameters and response schemas.

Parameters:operation_keys (tuple[str]) – an array of keys describing the hierarchical layout of this view in the API; e.g. ('snippets', 'list'), ('snippets', 'retrieve'), etc.
Return type:openapi.Operation
get_paginated_response(response_schema)[source]

Add appropriate paging fields to a response Schema.

Parameters:response_schema (openapi.Schema) – the response schema that must be paged.
Returns:the paginated response class:.Schema, or None in case of an unknown pagination scheme
Return type:openapi.Schema
get_pagination_parameters()[source]

Return the parameters added to the view by its paginator.

Return type:list[openapi.Parameter]
has_list_response()[source]

Determine whether this view returns multiple objects. By default this is any non-detail view (see is_list_view()) whose request method is one of implicit_list_response_methods.

Return type:bool
implicit_body_methods = ('PUT', 'PATCH', 'POST')
implicit_list_response_methods = ('GET',)
is_list_view()[source]

Determine whether this view is a list or a detail view. The difference between the two is that detail views depend on a pk/id path parameter. Note that a non-detail view does not necessarily imply a list reponse (has_list_response()), nor are list responses limited to non-detail views.

For example, one might have a /topic/<pk>/posts endpoint which is a detail view that has a list response.

Return type:bool
paginator_inspectors = [<class 'drf_yasg.inspectors.query.DjangoRestResponsePagination'>, <class 'drf_yasg.inspectors.query.CoreAPICompatInspector'>]
serializer_to_parameters(serializer, in_)[source]

Convert a serializer to a possibly empty list of Parameters.

Parameters:
  • serializer (serializers.BaseSerializer) – the Serializer instance
  • in (str) – the location of the parameters, one of the openapi.IN_* constants
Return type:

list[openapi.Parameter]

serializer_to_schema(serializer)[source]

Convert a serializer to an OpenAPI Schema.

Parameters:serializer (serializers.BaseSerializer) – the Serializer instance
Returns:the converted Schema, or None in case of an unknown serializer
Return type:openapi.Schema or openapi.SchemaRef
should_filter()[source]

Determine whether filter backend parameters should be included for this request.

Return type:bool
should_page()[source]

Determine whether paging parameters and structure should be added to this operation’s request and response.

Return type:bool
class drf_yasg.inspectors.CoreAPICompatInspector(view, path, method, components, request)

Bases: drf_yasg.inspectors.PaginatorInspector, drf_yasg.inspectors.FilterInspector

Converts coreapi.Fields to openapi.Parameters for filters and paginators that implement a get_schema_fields method.

Parameters:
  • view (rest_framework.views.APIView) – the view associated with this endpoint
  • path (str) – the path component of the operation URL
  • method (str) – the http method of the operation
  • components (openapi.ReferenceResolver) – referenceable components
  • request (rest_framework.request.Request) – the request made against the schema view; can be None
coreapi_field_to_parameter(field)[source]

Convert an instance of coreapi.Field to a swagger Parameter object.

Parameters:field (coreapi.Field) –
Return type:openapi.Parameter
get_filter_parameters(filter_backend)[source]

Get the filter parameters for a single filter backend instance.

Should return NotHandled if this inspector does not know how to handle the given filter_backend.

Parameters:filter_backend (BaseFilterBackend) – the filter backend
Return type:list[openapi.Parameter]
get_paginator_parameters(paginator)[source]

Get the pagination parameters for a single paginator instance.

Should return NotHandled if this inspector does not know how to handle the given paginator.

Parameters:paginator (BasePagination) – the paginator
Return type:list[openapi.Parameter]
class drf_yasg.inspectors.DjangoRestResponsePagination(view, path, method, components, request)

Bases: drf_yasg.inspectors.PaginatorInspector

Provides response schema pagination warpping for django-rest-framework’s LimitOffsetPagination, PageNumberPagination and CursorPagination

Parameters:
  • view (rest_framework.views.APIView) – the view associated with this endpoint
  • path (str) – the path component of the operation URL
  • method (str) – the http method of the operation
  • components (openapi.ReferenceResolver) – referenceable components
  • request (rest_framework.request.Request) – the request made against the schema view; can be None
get_paginated_response(paginator, response_schema)[source]

Add appropriate paging fields to a response Schema.

Should return NotHandled if this inspector does not know how to handle the given paginator.

Parameters:
  • paginator (BasePagination) – the paginator
  • response_schema (openapi.Schema) – the response schema that must be paged.
Return type:

openapi.Schema

class drf_yasg.inspectors.InlineSerializerInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.SerializerInspector

Provides serializer conversions using FieldInspector.field_to_swagger_object().

_has_ref_name(serializer)[source]
add_manual_parameters(serializer, parameters)[source]

Add/replace parameters from the given list of automatically generated request parameters. This method is called only when the serializer is converted into a list of parameters for use in a form data request.

Parameters:
  • serializer – serializer instance
  • parameters (list[openapi.Parameter]) – genereated parameters
Returns:

modified parameters

Return type:

list[openapi.Parameter]

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

get_parameter_name(field_name)[source]
get_property_name(field_name)[source]
get_request_parameters(serializer, in_)[source]

Convert a DRF serializer into a list of Parameters.

Should return NotHandled if this inspector does not know how to handle the given serializer.

Parameters:
  • serializer (serializers.BaseSerializer) – the Serializer instance
  • in (str) – the location of the parameters, one of the openapi.IN_* constants
Return type:

list[openapi.Parameter]

get_schema(serializer)[source]

Convert a DRF Serializer instance to an openapi.Schema.

Should return NotHandled if this inspector does not know how to handle the given serializer.

Parameters:serializer (serializers.BaseSerializer) – the Serializer instance
Return type:openapi.Schema
get_serializer_ref_name(serializer)[source]
use_definitions = False
class drf_yasg.inspectors.RecursiveFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Provides conversion for RecursiveField (https://github.com/heywbj/django-rest-framework-recursive)

class drf_yasg.inspectors.ReferencingSerializerInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.InlineSerializerInspector

use_definitions = True
class drf_yasg.inspectors.RelatedFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Provides conversions for RelatedFields.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.SimpleFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Provides conversions for fields which can be described using just type, format, pattern and min/max validators.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.FileFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Provides conversions for FileFields.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.ChoiceFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Provides conversions for ChoiceField and MultipleChoiceField.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.DictFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Provides conversion for DictField.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.StringDefaultFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

For otherwise unhandled fields, return them as plain TYPE_STRING objects.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.CamelCaseJSONFilter(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Converts property names to camelCase if djangorestframework_camel_case is used.

camelize_schema(schema)[source]

Recursively camelize property names for the given schema using djangorestframework_camel_case. The target schema object must be modified in-place.

Parameters:schema (openapi.Schema) – the Schema object
camelize_string(s)[source]

Hack to force djangorestframework_camel_case to camelize a plain string.

Parameters:s (str) – the string
Returns:camelized string
Return type:str
is_camel_case()[source]
process_result(result, method_name, obj, **kwargs)[source]

After an inspector handles an object (i.e. returns a value other than NotHandled), all inspectors that were probed get the chance to alter the result, in reverse order. The inspector that handled the object is the first to receive a process_result call with the object it just returned.

This behaviour is similar to the Django request/response middleware processing.

If this inspector has no post-processing to do, it should just return result (the default implementation).

Parameters:
  • result – the return value of the winning inspector, or None if no inspector handled the object
  • method_name (str) – name of the method that was called on the inspector
  • obj – first argument passed to inspector method
  • kwargs – additional arguments passed to inspector method
Returns:

class drf_yasg.inspectors.HiddenFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Hide HiddenField.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.SerializerMethodFieldInspector(view, path, method, components, request, field_inspectors)

Bases: drf_yasg.inspectors.FieldInspector

Provides conversion for SerializerMethodField, optionally using information from the swagger_serializer_method decorator.

field_to_swagger_object(field, swagger_object_type, use_references, **kwargs)[source]

Convert a drf Serializer or Field instance into a Swagger object.

Should return NotHandled if this inspector does not know how to handle the given field.

Parameters:
  • field (rest_framework.serializers.Field) – the source field
  • swagger_object_type (type[openapi.SwaggerDict]) – should be one of Schema, Parameter, Items
  • use_references (bool) – if False, forces all objects to be declared inline instead of by referencing other components
  • kwargs – extra attributes for constructing the object; if swagger_object_type is Parameter, name and in_ should be provided
Returns:

the swagger object

Return type:

openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef

class drf_yasg.inspectors.SwaggerAutoSchema(view, path, method, components, request, overrides)

Bases: drf_yasg.inspectors.ViewInspector

_get_request_body_override()[source]

Parse the request_body key in the override dict. This method is not public API.

add_manual_parameters(parameters)[source]

Add/replace parameters from the given list of automatically generated request parameters.

Parameters:parameters (list[openapi.Parameter]) – genereated parameters
Returns:modified parameters
Return type:list[openapi.Parameter]
get_consumes()[source]

Return the MIME types this endpoint can consume.

Return type:list[str]
get_default_response_serializer()[source]

Return the default response serializer for this endpoint. This is derived from either the request_body override or the request serializer (get_view_serializer()).

Returns:response serializer, Schema, SchemaRef, None
get_default_responses()[source]

Get the default responses determined for this view from the request serializer and request method.

Type:dict[str, openapi.Schema]
get_operation(operation_keys)[source]

Get an Operation for the given API endpoint (path, method). This includes query, body parameters and response schemas.

Parameters:operation_keys (tuple[str]) – an array of keys describing the hierarchical layout of this view in the API; e.g. ('snippets', 'list'), ('snippets', 'retrieve'), etc.
Return type:openapi.Operation
get_operation_id(operation_keys)[source]

Return an unique ID for this operation. The ID must be unique across all Operation objects in the API.

Parameters:operation_keys (tuple[str]) – an array of keys derived from the pathdescribing the hierarchical layout of this view in the API; e.g. ('snippets', 'list'), ('snippets', 'retrieve'), etc.
Return type:str
get_produces()[source]

Return the MIME types this endpoint can produce.

Return type:list[str]
get_query_parameters()[source]

Return the query parameters accepted by this view.

Return type:list[openapi.Parameter]
get_query_serializer()[source]

Return the query serializer (used for parsing query parameters) for this endpoint.

Returns:the query serializer, or None
get_request_body_parameters(consumes)[source]

Return the request body parameters for this view.
This is either:

  • a list with a single object Parameter with a Schema derived from the request serializer
  • a list of primitive Parameters parsed as form data
Parameters:consumes (list[str]) – a list of accepted MIME types as returned by get_consumes()
Returns:a (potentially empty) list of Parameters either in: body or in: formData
Return type:list[openapi.Parameter]
get_request_body_schema(serializer)[source]

Return the Schema for a given request’s body data. Only applies to PUT, PATCH and POST requests.

Parameters:serializer – the view’s request serializer as returned by get_request_serializer()
Return type:openapi.Schema
get_request_form_parameters(serializer)[source]

Given a Serializer, return a list of in: formData Parameters.

Parameters:serializer – the view’s request serializer as returned by get_request_serializer()
Return type:list[openapi.Parameter]
get_request_serializer()[source]

Return the request serializer (used for parsing the request payload) for this endpoint.

Returns:the request serializer, or one of Schema, SchemaRef, None
Return type:rest_framework.serializers.Serializer
get_response_schemas(response_serializers)[source]

Return the openapi.Response objects calculated for this view.

Parameters:response_serializers (dict) – response serializers as returned by get_response_serializers()
Returns:a dictionary of status code to Response object
Return type:dict[str, openapi.Response]
get_response_serializers()[source]

Return the response codes that this view is expected to return, and the serializer for each response body. The return value should be a dict where the keys are possible status codes, and values are either strings, Serializers, Schema, SchemaRef or Response objects. See @swagger_auto_schema for more details.

Returns:the response serializers
Return type:dict
get_responses()[source]

Get the possible responses for this view as a swagger Responses object.

Returns:the documented responses
Return type:openapi.Responses
get_security()[source]

Return a list of security requirements for this operation.

Returning an empty list marks the endpoint as unauthenticated (i.e. removes all accepted authentication schemes). Returning None will inherit the top-level secuirty requirements.

Returns:security requirements
Return type:list[dict[str,list[str]]]
get_summary_and_description()[source]

Return an operation summary and description determined from the view’s docstring.

Returns:summary and description
Return type:(str,str)
get_tags(operation_keys)[source]

Get a list of tags for this operation. Tags determine how operations relate with each other, and in the UI each tag will show as a group containing the operations that use it. If not provided in overrides, tags will be inferred from the operation url.

Parameters:operation_keys (tuple[str]) – an array of keys derived from the pathdescribing the hierarchical layout of this view in the API; e.g. ('snippets', 'list'), ('snippets', 'retrieve'), etc.
Return type:list[str]
get_view_serializer()[source]

Return the serializer as defined by the view’s get_serializer() method.

Returns:the view’s Serializer
Return type:rest_framework.serializers.Serializer
is_deprecated()[source]

Return True if this operation is to be marked as deprecated.

Returns:deprecation status
Return type:bool
make_body_parameter(schema)[source]

Given a Schema object, create an in: body Parameter.

Parameters:schema (openapi.Schema) – the request body schema
Return type:openapi.Parameter
split_summary_from_description(description)[source]

Decide if and how to split a summary out of the given description. The default implementation uses the first paragraph of the description as a summary if it is less than 120 characters long.

Parameters:description – the full description to be analyzed
Returns:summary and description
Return type:(str,str)

drf_yasg.middleware

class drf_yasg.middleware.SwaggerExceptionMiddleware(get_response)[source]

Bases: object

process_exception(request, exception)[source]

drf_yasg.openapi

drf_yasg.openapi.TYPE_OBJECT = 'object'
drf_yasg.openapi.TYPE_STRING = 'string'
drf_yasg.openapi.TYPE_NUMBER = 'number'
drf_yasg.openapi.TYPE_INTEGER = 'integer'
drf_yasg.openapi.TYPE_BOOLEAN = 'boolean'
drf_yasg.openapi.TYPE_ARRAY = 'array'
drf_yasg.openapi.TYPE_FILE = 'file'
drf_yasg.openapi.FORMAT_DATE = 'date'
drf_yasg.openapi.FORMAT_DATETIME = 'date-time'
drf_yasg.openapi.FORMAT_PASSWORD = 'password'
drf_yasg.openapi.FORMAT_BINARY = 'binary'
drf_yasg.openapi.FORMAT_BASE64 = 'bytes'
drf_yasg.openapi.FORMAT_FLOAT = 'float'
drf_yasg.openapi.FORMAT_DOUBLE = 'double'
drf_yasg.openapi.FORMAT_INT32 = 'int32'
drf_yasg.openapi.FORMAT_INT64 = 'int64'
drf_yasg.openapi.FORMAT_EMAIL = 'email'
drf_yasg.openapi.FORMAT_IPV4 = 'ipv4'
drf_yasg.openapi.FORMAT_IPV6 = 'ipv6'
drf_yasg.openapi.FORMAT_URI = 'uri'
drf_yasg.openapi.FORMAT_UUID = 'uuid'
drf_yasg.openapi.FORMAT_SLUG = 'slug'
drf_yasg.openapi.IN_BODY = 'body'
drf_yasg.openapi.IN_PATH = 'path'
drf_yasg.openapi.IN_QUERY = 'query'
drf_yasg.openapi.IN_FORM = 'formData'
drf_yasg.openapi.IN_HEADER = 'header'
drf_yasg.openapi.SCHEMA_DEFINITIONS = 'definitions'
drf_yasg.openapi.make_swagger_name(attribute_name)[source]

Convert a python variable name into a Swagger spec attribute name.

In particular,
  • if name starts with x_, return x-{camelCase}
  • if name is ref, return $ref
  • else return the name converted to camelCase, with trailing underscores stripped
Parameters:attribute_name (str) – python attribute name
Returns:swagger name
class drf_yasg.openapi.SwaggerDict(**attrs)[source]

Bases: collections.OrderedDict

A particular type of OrderedDict, which maps all attribute accesses to dict lookups using make_swagger_name(). Attribute names starting with _ are set on the object as-is and are not included in the specification output.

Used as a base class for all Swagger helper models.

_insert_extras__()[source]

From an ordering perspective, it is desired that extra attributes such as vendor extensions stay at the bottom of the object. However, python2.7’s OrderdDict craps out if you try to insert into it before calling init. This means that subclasses must call super().__init__ as the first statement of their own __init__, which would result in the extra attributes being added first. For this reason, we defer the insertion of the attributes and require that subclasses call ._insert_extras__ at the end of their __init__ method.

static _as_odict(obj, memo)[source]

Implementation detail of as_odict()

as_odict()[source]

Convert this object into an OrderedDict instance.

Return type:OrderedDict
class drf_yasg.openapi.Contact(name=None, url=None, email=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Swagger Contact object

At least one of the following fields is required:

Parameters:
  • name (str) – contact name
  • url (str) – contact url
  • email (str) – contact e-mail
class drf_yasg.openapi.License(name, url=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Swagger License object

Parameters:
  • name (str) – Required. License name
  • url (str) – link to detailed license information
class drf_yasg.openapi.Info(title, default_version, description=None, terms_of_service=None, contact=None, license=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Swagger Info object

Parameters:
  • title (str) – Required. API title.
  • default_version (str) – Required. API version string (not to be confused with Swagger spec version)
  • description (str) – API description; markdown supported
  • terms_of_service (str) – API terms of service; should be a URL
  • contact (Contact) – contact object
  • license (License) – license object
class drf_yasg.openapi.Swagger(info=None, _url=None, _prefix=None, _version=None, consumes=None, produces=None, security_definitions=None, security=None, paths=None, definitions=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Root Swagger object.

Parameters:
  • info (Info) – info object
  • _url (str) – URL used for setting the API host and scheme
  • _prefix (str) – api path prefix to use in setting basePath; this will be appended to the wsgi SCRIPT_NAME prefix or Django’s FORCE_SCRIPT_NAME if applicable
  • _version (str) – version string to override Info
  • security_definitions (dict[str,dict]) – list of supported authentication mechanisms
  • security (list[dict[str,list[str]]]) – authentication mechanisms accepted globally
  • consumes (list[str]) – consumed MIME types; can be overriden in Operation
  • produces (list[str]) – produced MIME types; can be overriden in Operation
  • paths (Paths) – paths object
  • definitions (dict[str,Schema]) – named models
classmethod get_base_path(script_prefix, api_prefix)[source]

Determine an appropriate value for basePath based on the SCRIPT_NAME and the api common prefix.

Parameters:
  • script_prefix (str) – script prefix as defined by django get_script_prefix
  • api_prefix (str) – api common prefix
Returns:

joined base path

class drf_yasg.openapi.Paths(paths, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

A listing of all the paths in the API.

Parameters:paths (dict[str,PathItem]) –
class drf_yasg.openapi.PathItem(get=None, put=None, post=None, delete=None, options=None, head=None, patch=None, parameters=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Information about a single path

Parameters:
  • get (Operation) – operation for GET
  • put (Operation) – operation for PUT
  • post (Operation) – operation for POST
  • delete (Operation) – operation for DELETE
  • options (Operation) – operation for OPTIONS
  • head (Operation) – operation for HEAD
  • patch (Operation) – operation for PATCH
  • parameters (list[Parameter]) – parameters that apply to all operations
OPERATION_NAMES = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch']
operations

A list of all standard Operations on this PathItem object. See OPERATION_NAMES.

Returns:list of (method name, Operation) tuples
Return type:list[tuple[str,Operation]]
class drf_yasg.openapi.Operation(operation_id, responses, parameters=None, consumes=None, produces=None, summary=None, description=None, tags=None, security=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Information about an API operation (path + http method combination)

Parameters:
  • operation_id (str) – operation ID, should be unique across all operations
  • responses (Responses) – responses returned
  • parameters (list[Parameter]) – parameters accepted
  • consumes (list[str]) – content types accepted
  • produces (list[str]) – content types produced
  • summary (str) – operation summary; should be < 120 characters
  • description (str) – operation description; can be of any length and supports markdown
  • tags (list[str]) – operation tags
  • security (list[dict[str,list[str]]]) – list of security requirements
drf_yasg.openapi._check_type(type, format, enum, pattern, items, _obj_type)[source]
class drf_yasg.openapi.Items(type=None, format=None, enum=None, pattern=None, items=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Used when defining an array Parameter to describe the array elements.

Parameters:
  • type (str) – type of the array elements; must not be object
  • format (str) – value format, see OpenAPI spec
  • enum (list) – restrict possible values
  • pattern (str) – pattern if type is string
  • items (Items) – only valid if type is array
class drf_yasg.openapi.Parameter(name, in_, description=None, required=None, schema=None, type=None, format=None, enum=None, pattern=None, items=None, default=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Describe parameters accepted by an Operation. Each parameter should be a unique combination of (name, in_). body and form parameters in the same operation are mutually exclusive.

Parameters:
  • name (str) – parameter name
  • in (str) – parameter location
  • description (str) – parameter description
  • required (bool) – whether the parameter is required for the operation
  • schema (Schema or SchemaRef) – required if in_ is body
  • type (str) – parameter type; required if in_ is not body; must not be object
  • format (str) – value format, see OpenAPI spec
  • enum (list) – restrict possible values
  • pattern (str) – pattern if type is string
  • items (Items) – only valid if type is array
  • default – default value if the parameter is not provided; must conform to parameter type
class drf_yasg.openapi.Schema(title=None, description=None, type=None, format=None, enum=None, pattern=None, properties=None, additional_properties=None, required=None, items=None, default=None, read_only=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Describes a complex object accepted as parameter or returned as a response.

Parameters:
  • title (str) – schema title
  • description (str) – schema description
  • type (str) – value type; required
  • format (str) – value format, see OpenAPI spec
  • enum (list) – restrict possible values
  • pattern (str) – pattern if type is string
  • properties (dict[str,Schema or SchemaRef]) – object properties; required if type is object
  • additional_properties (bool or Schema or SchemaRef) – allow wildcard properties not listed in properties
  • required (list[str]) – list of requried property names
  • items (Schema or SchemaRef) – type of array items, only valid if type is array
  • default – only valid when insider another Schema’s properties; the default value of this property if it is not provided, must conform to the type of this Schema
  • read_only – only valid when insider another Schema’s properties; declares the property as read only - it must only be sent as part of responses, never in requests
OR_REF = (<class 'drf_yasg.openapi.Schema'>, <class 'drf_yasg.openapi.SchemaRef'>)

useful for type-checking, e.g isinstance(obj, openapi.Schema.OR_REF)

_remove_read_only()[source]
class drf_yasg.openapi._Ref(resolver, name, scope, expected_type, ignore_unresolved=False)[source]

Bases: drf_yasg.openapi.SwaggerDict

Base class for all reference types. A reference object has only one property, $ref, which must be a JSON reference to a valid object in the specification, e.g. #/definitions/Article to refer to an article model.

Parameters:
  • resolver (ReferenceResolver) – component resolver which must contain the referneced object
  • name (str) – referenced object name, e.g. “Article”
  • scope (str) – reference scope, e.g. “definitions”
  • expected_type (type[SwaggerDict]) – the expected type that will be asserted on the object found in resolver
  • ignore_unresolved (bool) – do not throw if the referenced object does not exist
ref_name_re = re.compile('#/(?P<scope>.+)/(?P<name>[^/]+)$')
resolve(resolver)[source]

Get the object targeted by this reference from the given component resolver.

Parameters:resolver (ReferenceResolver) – component resolver which must contain the referneced object
Returns:the target object
class drf_yasg.openapi.SchemaRef(resolver, schema_name, ignore_unresolved=False)[source]

Bases: drf_yasg.openapi._Ref

Adds a reference to a named Schema defined in the #/definitions/ object.

Parameters:
  • resolver (ReferenceResolver) – component resolver which must contain the definition
  • schema_name (str) – schema name
  • ignore_unresolved (bool) – do not throw if the referenced object does not exist
drf_yasg.openapi.resolve_ref(ref_or_obj, resolver)[source]

Resolve ref_or_obj if it is a reference type. Return it unchaged if not.

Parameters:
  • ref_or_obj (SwaggerDict or _Ref) – object to derefernece
  • resolver – component resolver which must contain the referenced object
class drf_yasg.openapi.Responses(responses, default=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Describes the expected responses of an Operation.

Parameters:
  • responses (dict[str or int,Response]) – mapping of status code to response definition
  • default (Response) – description of the response structure to expect if another status code is returned
class drf_yasg.openapi.Response(description, schema=None, examples=None, **extra)[source]

Bases: drf_yasg.openapi.SwaggerDict

Describes the structure of an operation’s response.

Parameters:
  • description (str) – response description
  • schema (Schema or SchemaRef or rest_framework.serializers.Serializer or type[rest_framework.serializers.Serializer]) – sturcture of the response body
  • examples (dict) – example bodies mapped by mime type
class drf_yasg.openapi.ReferenceResolver(*scopes, **kwargs)[source]

Bases: object

A mapping type intended for storing objects pointed at by Swagger Refs. Provides support and checks for different refernce scopes, e.g. ‘definitions’.

For example:

> components = ReferenceResolver('definitions', 'parameters')
> definitions = components.with_scope('definitions')
> definitions.set('Article', Schema(...))
> print(components)
{'definitions': OrderedDict([('Article', Schema(...)]), 'parameters': OrderedDict()}
Parameters:scopes (str) – an enumeration of the valid scopes this resolver will contain
with_scope(scope)[source]

Return a view into this ReferenceResolver whose scope is defaulted and forced to scope.

Parameters:scope (str) – target scope, must be in this resolver’s scopes
Returns:the bound resolver
Return type:ReferenceResolver
_check_scope(scope)[source]
set(name, obj, scope=None)[source]

Set an object in the given scope, raise an error if it already exists.

Parameters:
  • name (str) – reference name
  • obj – referenced object
  • scope (str) – reference scope
setdefault(name, maker, scope=None)[source]

Set an object in the given scope only if it does not exist.

Parameters:
  • name (str) – reference name
  • maker (function) – object factory, called only if necessary
  • scope (str) – reference scope
get(name, scope=None)[source]

Get an object from the given scope, raise an error if it does not exist.

Parameters:
  • name (str) – reference name
  • scope (str) – reference scope
Returns:

the object

getdefault(name, default=None, scope=None)[source]

Get an object from the given scope or a default value if it does not exist.

Parameters:
  • name (str) – reference name
  • default – the default value
  • scope (str) – reference scope
Returns:

the object or default

has(name, scope=None)[source]

Check if an object exists in the given scope.

Parameters:
  • name (str) – reference name
  • scope (str) – reference scope
Returns:

True if the object exists

Return type:

bool

scopes
keys()[source]

drf_yasg.renderers

class drf_yasg.renderers._SpecRenderer[source]

Bases: rest_framework.renderers.BaseRenderer

Base class for text renderers. Handles encoding and validation.

charset = 'utf-8'
validators = []
codec_class = None
classmethod with_validators(validators)[source]
render(data, media_type=None, renderer_context=None)[source]
class drf_yasg.renderers.OpenAPIRenderer[source]

Bases: drf_yasg.renderers._SpecRenderer

Renders the schema as a JSON document with the application/openapi+json specific mime type.

media_type = 'application/openapi+json'
format = 'openapi'
codec_class

alias of drf_yasg.codecs.OpenAPICodecJson

class drf_yasg.renderers.SwaggerJSONRenderer[source]

Bases: drf_yasg.renderers._SpecRenderer

Renders the schema as a JSON document with the generic application/json mime type.

media_type = 'application/json'
format = '.json'
codec_class

alias of drf_yasg.codecs.OpenAPICodecJson

class drf_yasg.renderers.SwaggerYAMLRenderer[source]

Bases: drf_yasg.renderers._SpecRenderer

Renders the schema as a YAML document.

media_type = 'application/yaml'
format = '.yaml'
codec_class

alias of drf_yasg.codecs.OpenAPICodecYaml

class drf_yasg.renderers._UIRenderer[source]

Bases: rest_framework.renderers.BaseRenderer

Base class for web UI renderers. Handles loading and passing settings to the appropriate template.

media_type = 'text/html'
charset = 'utf-8'
template = ''
render(swagger, accepted_media_type=None, renderer_context=None)[source]
set_context(renderer_context, swagger=None)[source]
resolve_url(to)[source]
get_auth_urls()[source]
get_oauth2_config()[source]
class drf_yasg.renderers.SwaggerUIRenderer[source]

Bases: drf_yasg.renderers._UIRenderer

Renders a swagger-ui web interface for schema browisng.

template = 'drf-yasg/swagger-ui.html'
format = 'swagger'
set_context(renderer_context, swagger=None)[source]
get_swagger_ui_settings()[source]
class drf_yasg.renderers.ReDocRenderer[source]

Bases: drf_yasg.renderers._UIRenderer

Renders a ReDoc web interface for schema browisng.

template = 'drf-yasg/redoc.html'
format = 'redoc'
set_context(renderer_context, swagger=None)[source]
get_redoc_settings()[source]
class drf_yasg.renderers.ReDocOldRenderer[source]

Bases: drf_yasg.renderers.ReDocRenderer

Renders a ReDoc 1.x.x web interface for schema browisng.

template = 'drf-yasg/redoc-old.html'

drf_yasg.utils

class drf_yasg.utils.no_body[source]

Bases: object

Used as a sentinel value to forcibly remove the body of a request via swagger_auto_schema().

class drf_yasg.utils.unset[source]

Bases: object

Used as a sentinel value for function parameters not set by the caller where None would be a valid value.

drf_yasg.utils.swagger_auto_schema(method=None, methods=None, auto_schema=<class 'drf_yasg.utils.unset'>, request_body=None, query_serializer=None, manual_parameters=None, operation_id=None, operation_description=None, operation_summary=None, security=None, deprecated=None, responses=None, field_inspectors=None, filter_inspectors=None, paginator_inspectors=None, tags=None, **extra_overrides)[source]

Decorate a view method to customize the Operation object generated from it.

method and methods are mutually exclusive and must only be present when decorating a view method that accepts more than one HTTP request method.

The auto_schema and operation_description arguments take precendence over view- or method-level values.

Parameters:
  • method (str) – for multi-method views, the http method the options should apply to
  • methods (list[str]) – for multi-method views, the http methods the options should apply to
  • auto_schema (drf_yasg.inspectors.SwaggerAutoSchema) – custom class to use for generating the Operation object; this overrides both the class-level swagger_schema attribute and the DEFAULT_AUTO_SCHEMA_CLASS setting, and can be set to None to prevent this operation from being generated
  • request_body (drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or rest_framework.serializers.Serializer or type[no_body]) –

    custom request body which will be used as the schema property of a Parameter with in: 'body'.

    A Schema or SchemaRef is not valid if this request consumes form-data, because form and body parameters are mutually exclusive in an Operation. If you need to set custom form parameters, you can use the manual_parameters argument.

    If a Serializer class or instance is given, it will be automatically converted into a Schema used as a body Parameter, or into a list of form Parameters, as appropriate.

  • query_serializer (rest_framework.serializers.Serializer) –

    if you use a Serializer to parse query parameters, you can pass it here and have Parameter objects be generated automatically from it.

    If any Field on the serializer cannot be represented as a query Parameter (e.g. nested Serializers, file fields, …), the schema generation will fail with an error.

    Schema generation will also fail if the name of any Field on the query_serializer conflicts with parameters generated by filter_backends or paginator.

  • manual_parameters (list[drf_yasg.openapi.Parameter]) –

    a list of manual parameters to override the automatically generated ones

    Parameters are identified by their (name, in) combination, and any parameters given here will fully override automatically generated parameters if they collide.

    It is an error to supply form parameters when the request does not consume form-data.

  • operation_id (str) – operation ID override; the operation ID must be unique accross the whole API
  • operation_description (str) – operation description override
  • operation_summary (str) – operation summary string
  • security (list[dict]) – security requirements override; used to specify which authetication mechanism is requried to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted authentication schemes), and None will inherit the top-level secuirty requirements
  • deprecated (bool) – deprecation status for operation
  • responses (dict[str,(drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or drf_yasg.openapi.Response or str or rest_framework.serializers.Serializer)]) –

    a dict of documented manual responses keyed on response status code. If no success (2xx) response is given, one will automatically be generated from the request body and http method. If any 2xx response is given the automatic response is suppressed.

    • if a plain string is given as value, a Response with no body and that string as its description will be generated
    • if None is given as a value, the response is ignored; this is mainly useful for disabling default 2xx responses, i.e. responses={200: None, 302: 'something'}
    • if a Schema, SchemaRef is given, a Response with the schema as its body and an empty description will be generated
    • a Serializer class or instance will be converted into a Schema and treated as above
    • a Response object will be used as-is; however if its schema attribute is a Serializer, it will automatically be converted into a Schema
  • field_inspectors (list[type[drf_yasg.inspectors.FieldInspector]]) – extra serializer and field inspectors; these will be tried before ViewInspector.field_inspectors on the inspectors.SwaggerAutoSchema
  • filter_inspectors (list[type[drf_yasg.inspectors.FilterInspector]]) – extra filter inspectors; these will be tried before ViewInspector.filter_inspectors on the inspectors.SwaggerAutoSchema
  • paginator_inspectors (list[type[drf_yasg.inspectors.PaginatorInspector]]) – extra paginator inspectors; these will be tried before ViewInspector.paginator_inspectors on the inspectors.SwaggerAutoSchema
  • tags (list[str]) – tags override
  • extra_overrides – extra values that will be saved into the overrides dict; these values will be available in the handling inspectors.SwaggerAutoSchema instance via self.overrides
drf_yasg.utils.swagger_serializer_method(serializer_or_field)[source]

Decorates the method of a serializers.SerializerMethodField to hint as to how Swagger should be generated for this field.

Parameters:serializer_or_fieldSerializer/Field class or instance
Returns:
drf_yasg.utils.is_list_view(path, method, view)[source]

Check if the given path/method appears to represent a list view (as opposed to a detail/instance view).

Parameters:
  • path (str) – view path
  • method (str) – http method
  • view (APIView) – target view
Return type:

bool

drf_yasg.utils.guess_response_status(method)[source]
drf_yasg.utils.param_list_to_odict(parameters)[source]

Transform a list of Parameter objects into an OrderedDict keyed on the (name, in_) tuple of each parameter.

Raises an AssertionError if parameters contains duplicate parameters (by their name + in combination).

Parameters:parameters (list[drf_yasg.openapi.Parameter]) – the list of parameters
Returns:parameters keyed by (name, in_)
Return type:dict[(str,str),drf_yasg.openapi.Parameter]
drf_yasg.utils.merge_params(parameters, overrides)[source]

Merge overrides into parameters. This is the same as appending overrides to parameters, but any element of parameters whose (name, in_) tuple collides with an element in overrides is replaced by it.

Raises an AssertionError if either list contains duplicate parameters.

Parameters:
Returns:

merged list

Return type:

list[drf_yasg.openapi.Parameter]

drf_yasg.utils.filter_none(obj)[source]

Remove None values from tuples, lists or dictionaries. Return other objects as-is.

Parameters:obj – the object
Returns:collection with None values removed
drf_yasg.utils.force_serializer_instance(serializer)[source]

Force serializer into a Serializer instance. If it is not a Serializer class or instance, raises an assertion error.

Parameters:serializer (serializers.BaseSerializer or type[serializers.BaseSerializer]) – serializer class or instance
Returns:serializer instance
Return type:serializers.BaseSerializer
drf_yasg.utils.get_serializer_class(serializer)[source]

Given a Serializer class or intance, return the Serializer class. If serializer is not a Serializer class or instance, raises an assertion error.

Parameters:serializer – serializer class or instance, or None
Returns:serializer class
Return type:type[serializers.BaseSerializer]
drf_yasg.utils.get_object_classes(classes_or_instances, expected_base_class=None)[source]

Given a list of instances or class objects, return the list of their classes.

Parameters:
  • classes_or_instances (list[type or object]) – mixed list to parse
  • expected_base_class (type) – if given, only subclasses or instances of this type will be returned
Returns:

list of classes

Return type:

list

drf_yasg.utils.get_consumes(parser_classes)[source]

Extract consumes MIME types from a list of parser classes.

Parameters:parser_classes (list[rest_framework.parsers.BaseParser or type[rest_framework.parsers.BaseParser]]) – parser classes
Returns:MIME types for consumes
Return type:list[str]
drf_yasg.utils.get_produces(renderer_classes)[source]

Extract produces MIME types from a list of renderer classes.

Parameters:renderer_classes (list[rest_framework.renderers.BaseRenderer or type[rest_framework.renderers.BaseRenderer]]) – renderer classes
Returns:MIME types for produces
Return type:list[str]
drf_yasg.utils.decimal_as_float(field)[source]

Returns true if field is a django-rest-framework DecimalField and its coerce_to_string attribute or the COERCE_DECIMAL_TO_STRING setting is set to False.

Return type:bool
drf_yasg.utils.get_serializer_ref_name(serializer)[source]

Get serializer’s ref_name (or None for ModelSerializer if it is named ‘NestedSerializer’)

Parameters:serializer – Serializer instance
Returns:Serializer’s ref_name or None for inline serializer
Return type:str or None
drf_yasg.utils.force_real_str(s, encoding='utf-8', strings_only=False, errors='strict')[source]

Force s into a str instance.

Fix for https://github.com/axnsan12/drf-yasg/issues/159

drf_yasg.utils.field_value_to_representation(field, value)[source]

Convert a python value related to a field (default, choices, etc.) into its OpenAPI-compatible representation.

Parameters:
  • field (serializers.Field) – field associated with the value
  • value (object) – value
Returns:

the converted value

drf_yasg.utils.get_field_default(field)[source]

Get the default value for a field, converted to a JSON-compatible value while properly handling callables.

Parameters:field – field instance
Returns:default value
drf_yasg.utils.dict_has_ordered_keys(obj)[source]

Check if a given object is a dict that maintains insertion order.

Parameters:obj – the dict object to check
Return type:bool

drf_yasg.views

drf_yasg.views.deferred_never_cache(view_func)[source]

Decorator that adds headers to a response so that it will never be cached.

drf_yasg.views.get_schema_view(info=None, url=None, patterns=None, urlconf=None, public=False, validators=None, generator_class=None, authentication_classes=None, permission_classes=None)[source]

Create a SchemaView class with default renderers and generators.

Parameters:
  • info (Info) – information about the API; if omitted, defaults to DEFAULT_INFO
  • url (str) – same as OpenAPISchemaGenerator
  • patterns – same as OpenAPISchemaGenerator
  • urlconf – same as OpenAPISchemaGenerator
  • public (bool) – if False, includes only the endpoints that are accesible by the user viewing the schema
  • validators (list) – a list of validator names to apply; the only allowed value is ssv, for now
  • generator_class (type) – schema generator class to use; should be a subclass of OpenAPISchemaGenerator
  • authentication_classes (tuple) – authentication classes for the schema view itself
  • permission_classes (tuple) – permission classes for the schema view itself
Returns:

SchemaView class

Return type:

type[drf_yasg.views.SchemaView]

class drf_yasg.views.SchemaView(**kwargs)

Bases: rest_framework.views.APIView

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

_ignore_model_permissions = True
classmethod apply_cache(view, cache_timeout, cache_kwargs)

Override this method to customize how caching is applied to the view.

Arguments described in as_cached_view().

classmethod as_cached_view(cache_timeout=0, cache_kwargs=None, **initkwargs)

Calls .as_view() and wraps the result in a cache_page decorator. See https://docs.djangoproject.com/en/dev/topics/cache/

Parameters:
  • cache_timeout (int) – same as cache_page; set to 0 for no cache
  • cache_kwargs (dict) – dictionary of kwargs to be passed to cache_page
  • initkwargs – kwargs for .as_view()
Returns:

a view instance

authentication_classes = [<class 'rest_framework.authentication.SessionAuthentication'>, <class 'rest_framework.authentication.BasicAuthentication'>]
generator_class

alias of drf_yasg.generators.OpenAPISchemaGenerator

get(request, version='', format=None)
permission_classes = [<class 'rest_framework.permissions.AllowAny'>]
public = False
renderer_classes = (<class 'drf_yasg.renderers.SwaggerYAMLRenderer'>, <class 'drf_yasg.renderers.SwaggerJSONRenderer'>, <class 'drf_yasg.renderers.OpenAPIRenderer'>)
schema = None
classmethod with_ui(renderer='swagger', cache_timeout=0, cache_kwargs=None)

Instantiate this view with a Web UI renderer, optionally wrapped with cache_page. See https://docs.djangoproject.com/en/dev/topics/cache/.

Parameters:
  • renderer (str) – UI renderer; allowed values are swagger, redoc
  • cache_timeout (int) – same as cache_page; set to 0 for no cache
  • cache_kwargs (dict) – dictionary of kwargs to be passed to cache_page
Returns:

a view instance

classmethod without_ui(cache_timeout=0, cache_kwargs=None)

Instantiate this view with just JSON and YAML renderers, optionally wrapped with cache_page. See https://docs.djangoproject.com/en/dev/topics/cache/.

Parameters:
  • cache_timeout (int) – same as cache_page; set to 0 for no cache
  • cache_kwargs (dict) – dictionary of kwargs to be passed to cache_page
Returns:

a view instance