From drf-yasg to OpenAPI 3
drf-yasg is an excellent library and the most popular choice for generating OpenAPI 2.0 (formerly known as Swagger 2.0) schemas with Django REST Framework. Unfortunately, it currently does not provide support for OpenAPI 3.x. Migration from drf-yasg to drf-spectacular requires some modifications, the complexity of which depends on what features are being used.
Note
In contrast to drf-yasg, we don’t package Redoc & Swagger UI but serve them via hyperlinked CDNs instead. If you want or need to serve those files yourself, you can do that with the optional drf-spectacular-sidecar package. See installation instructions for further details.
Decorators
@swagger_auto_schemais largely equivalent to@extend_schema.operation_descriptionargument is calleddescriptionoperation_summaryargument is calledsummarymanual_parametersandquery_serializerarguments are merged into a singleparametersargumentsecurityargument is calledauthrequest_bodyarguments is calledrequestUse
Noneinstead ofdrf_yasg.utils.no_body
methodargument doesn’t exist, usemethodsinstead (also supported by drf-yasg)auto_schemahas no equivalent.extra_overrideshas no equivalent.field_inspectorshas no equivalent.filter_inspectorshas no equivalent.paginator_inspectorshas no equivalent.Additional arguments are also available:
exclude,operation,versions,examples.
@swagger_serializer_methodis equivalent to@extend_schema_field.component_namecan be provided to break the field out as a separate component.
@extend_schema_serializeris available for overriding behavior of serializers.Instead of using
@method_decorator, use@extend_schema_view.Instead of using
swagger_schema_field, use@extend_schema_fieldor@extend_schema_serializer.
Helper Classes
Parameteris roughly equivalent toOpenApiParameter.in_argument is calledlocation.schemaargument should be passed astype.formatargument is merged intotypeargument by usingOpenApiTypes.setting the
manyargument toTruecauses the argument to take an array of values, and generates a schema similar to using the drf_yasgItemsclass on theitemsproperty. The type of the items in the array are defined by thetypeargument.
Responseis largely identical toOpenApiResponse.schemaargument is calledresponseOrder of arguments differs, so use keyword arguments.
OpenApiExampleis available for providingexamplesto@extend_schema.Schemais not required and can be eliminated. Use a plaindictinstead.
Types & Formats
In place of separate drf_yasg.openapi.TYPE_* and drf_yasg.openapi.FORMAT_* constants, drf-spectacular
provides the OpenApiTypes enum:
TYPE_BOOLEANis calledBOOL, but you can usebool.TYPE_INTEGERis calledINT, but you can useint.TYPE_INTEGERwithFORMAT_INT32is calledINT32TYPE_INTEGERwithFORMAT_INT64is calledINT64TYPE_NUMBERis calledNUMBERTYPE_NUMBERwithFORMAT_FLOATis calledFLOAT, but you can usefloat.TYPE_NUMBERwithFORMAT_DOUBLEis calledDOUBLE(orDECIMAL, but you can useDecimal)TYPE_OBJECTis calledOBJECT, but you can usedict.TYPE_STRINGis calledSTR, but you can usestr.TYPE_STRINGwithFORMAT_BASE64is calledBYTE(which is base64 encoded).TYPE_STRINGwithFORMAT_BINARYis calledBINARY, but you can usebytes.TYPE_STRINGwithFORMAT_DATETIMEis calledDATETIME, but you can usedatetime.datetime.TYPE_STRINGwithFORMAT_DATEis calledDATE, but you can usedatetime.date.TYPE_STRINGwithFORMAT_EMAILis calledEMAILTYPE_STRINGwithFORMAT_IPV4is calledIP4, but you can useipaddress.IPv4Address.TYPE_STRINGwithFORMAT_IPV6is calledIP6, but you can useipaddress.IPv6Address.TYPE_STRINGwithFORMAT_PASSWORDis calledPASSWORDTYPE_STRINGwithFORMAT_URIis calledURITYPE_STRINGwithFORMAT_UUIDis calledUUID, but you can useuuid.UUID.TYPE_STRINGwithFORMAT_SLUGhas no direct equivalent. UseSTRorstrinstead.TYPE_ARRAYis handled by providingOpenApiParameterwithmany=Trueas a parameter. There is no need to set theitemsproperty on the parameter - the presence ofmany=Trueturns the parameter into an array parameter.The following additional types are also available:
ANYfor which you can usetyping.Any.DURATIONfor which you can usedatetime.timedelta.TIMEfor which you can usedatetime.time.
Parameter Location
drf_yasg.openapi.IN_* constants are roughtly equivalent to constants defined on the
OpenApiParameter class:
Docstring Parsing
drf-yasg has some special handling for docstrings that is not supported by drf-spectacular.
It attempts to split the first line from the rest of the docstring to use as the operation summary, and the remainder
is used as the operation description. drf-spectacular uses the entire docstring as the description. Use the
summary and description arguments of @extend_schema instead.
Optionally, the docstring can still be used to populate the operation description.
# Supported by drf-yasg:
class UserViewSet(ViewSet):
def list(self, request):
"""
List all the users.
Return a list of all usernames in the system.
"""
...
# Updated for drf-spectacular using decorator for description:
class UserViewSet(ViewSet):
@extend_schema(
summary="List all the users.",
description="Return a list of all usernames in the system.",
)
def list(self, request):
...
# Updated for drf-spectacular using docstring for description:
class UserViewSet(ViewSet):
@extend_schema(summary="List all the users.")
def list(self, request):
"""Return a list of all usernames in the system."""
...
In addition, drf-yasg also supports named sections, but these are not supported by drf-spectacular. Again,
use the summary and description arguments of @extend_schema
instead:
# Supported by drf-yasg:
class UserViewSet(ViewSet):
"""
list:
List all the users.
Return a list of all usernames in the system.
retrieve:
Retrieve user
Get details of a specific user
"""
...
# Updated for drf-spectacular using decorator for description:
@extend_schema_view(
list=extend_schema(
summary="List all the users.",
description="Return a list of all usernames in the system.",
),
retrieve=extend_schema(
summary="Retrieve user",
description="Get details of a specific user",
),
)
class UserViewSet(ViewSet):
...
Authentication
In drf-yasg it was necessary to manually describe authentication schemes.
In drf-spectacular there is support for auto-generating the security definitions for a number of authentication
classes built in to DRF as well as other popular third-party packages.
OpenApiAuthenticationExtension is available to help tie in custom
authentication clasees – see the customization guide.
Compatibility
For compatibility, the following features of drf-yasg have been implemented:
ref_nameonSerializerMetaclasses is supported (excluding inlining withref_name=None)See drf-yasg’s documentation for further details.
The equivalent in
drf-spectacularis@extend_schema_serializer(component_name="...")
swagger_fake_viewis available as attribute on views to signal schema generation