Package: drf-spectacular
Sane and flexibleOpenAPI(3.0.3&3.1) schema generation forDjango REST framework.This project has 3 goals:Extract as much schema information from DRF as possible.Provide flexibility to make the schema usable in the real world (not only toy examples).Generate a schema that works well with the most popular client generators.The code is a heavily modified fork of theDRF OpenAPI generator,
which is/was lacking all of the below listed features.FeaturesSerializers modelled as components. (arbitrary nesting and recursion supported)@extend_schemadecorator for customization of APIView, Viewsets, function-based views, and@actionadditional parametersrequest/response serializer override (with status codes)polymorphic responses either manually withPolymorphicProxySerializerhelper or viarest_polymorphic’s PolymorphicSerializer)… and more customization optionsAuthentication support (DRF natives included, easily extendable)Custom serializer class support (easily extendable)SerializerMethodField()type via type hinting or@extend_schema_fieldi18n supportTags extractionRequest/response/parameter examplesDescription extraction fromdocstringsVendor specification extensions (x-*) in info, operations, parameters, components, and security schemesSane fallbacksSaneoperation_idnaming (based on path)Schema serving withSpectacularAPIView(Redoc and Swagger-UI views are also available)Optional input/output serializer component splitCallback operationsOpenAPI 3.1 support (via settingOAS_VERSION)Included support for:django-polymorphic/django-rest-polymorphicSimpleJWTDjangoOAuthToolkitdjangorestframework-jwt(tested forkdrf-jwt)dj-rest-auth(maintained fork ofdjango-rest-auth)djangorestframework-camel-case(via postprocessing hookcamelize_serializer_fields)django-filterdrf-nested-routersdjangorestframework-recursivedjangorestframework-dataclassesdjango-rest-framework-gisPydantic (>=2.0)For more information visit thedocumentation.LicenseProvided byT. Franzel.Licensed under 3-Clause BSD.RequirementsPython >= 3.6Django (2.2, 3.2, 4.0, 4.1, 4.2, 5.0)Django REST Framework (3.10.3, 3.11, 3.12, 3.13, 3.14)InstallationInstall usingpip…$pipinstalldrf-spectacularthen add drf-spectacular to installed apps insettings.pyINSTALLED_APPS=[# ALL YOUR APPS'drf_spectacular',]and finally register our spectacular AutoSchema with DRF.REST_FRAMEWORK={# YOUR SETTINGS'DEFAULT_SCHEMA_CLASS':'drf_spectacular.openapi.AutoSchema',}drf-spectacular ships with sanedefault settingsthat should work reasonably well out of the box. It is not necessary to
specify any settings, but we recommend to specify at least some metadata.SPECTACULAR_SETTINGS={'TITLE':'Your Project API','DESCRIPTION':'Your project description','VERSION':'1.0.0','SERVE_INCLUDE_SCHEMA':False,# OTHER SETTINGS}Self-contained UI installationCertain environments have no direct access to the internet and as such are unable
to retrieve Swagger UI or Redoc from CDNs.drf-spectacular-sidecarprovides
these static files as a separate optional package. Usage is as follows:$pipinstalldrf-spectacular[sidecar]INSTALLED_APPS=[# ALL YOUR APPS'drf_spectacular','drf_spectacular_sidecar',# required for Django collectstatic discovery]SPECTACULAR_SETTINGS={'SWAGGER_UI_DIST':'SIDECAR',# shorthand to use the sidecar instead'SWAGGER_UI_FAVICON_HREF':'SIDECAR','REDOC_DIST':'SIDECAR',# OTHER SETTINGS}Release managementdrf-spectaculardeliberately stays below version1.x.xto signal that every
new version may potentially break you. For production we strongly recommend pinning the
version and inspecting a schema diff on update.With that said, we aim to be extremely defensive w.r.t. breaking API changes. However,
we also acknowledge the fact that even slight schema changes may break your toolchain,
as any existing bug may somehow also be used as a feature.We define version increments with the following semantics.y-streamincrements may contain
potentially breaking changes to both API and schema.z-streamincrements will never break the
API and may only contain schema changes that should have a low chance of breaking you.Take it for a spinGenerate your schema with the CLI:$./manage.pyspectacular--color--fileschema.yml$dockerrun-p80:8080-eSWAGGER_JSON=/schema.yml-v${PWD}/schema.yml:/schema.ymlswaggerapi/swagger-uiIf you also want to validate your schema add the--validateflag. Or serve your schema directly
from your API. We also provide convenience wrappers forswagger-uiorredoc.fromdrf_spectacular.viewsimportSpectacularAPIView,SpectacularRedocView,SpectacularSwaggerViewurlpatterns=[# YOUR PATTERNSpath('api/schema/',SpectacularAPIView.as_view(),name='schema'),# Optional UI:path('api/schema/swagger-ui/',SpectacularSwaggerView.as_view(url_name='schema'),name='swagger-ui'),path('api/schema/redoc/',SpectacularRedocView.as_view(url_name='schema'),name='redoc'),]Usagedrf-spectacularworks pretty well out of the box. You might also want to set some metadata for your API.
Just create aSPECTACULAR_SETTINGSdictionary in yoursettings.pyand override the defaults.
Have a look at theavailable settings.The toy examples do not cover your cases? No problem, you can heavily customize how your schema will be rendered.Customization by using@extend_schemaMost customization cases should be covered by theextend_schemadecorator. We usually get
pretty far with specifyingOpenApiParameterand splitting request/response serializers, but
the sky is the limit.fromdrf_spectacular.utilsimportextend_schema,OpenApiParameter,OpenApiExamplefromdrf_spectacular.typesimportOpenApiTypesclassAlbumViewset(viewset.ModelViewset):serializer_class=AlbumSerializer@extend_schema(request=AlbumCreationSerializer,responses={201:AlbumSerializer},)defcreate(self,request):# your non-standard behaviourreturnsuper().create(request)@extend_schema(# extra parameters added to the schemaparameters=[OpenApiParameter(name='artist',description='Filter by artist',required=False,type=str),OpenApiParameter(name='release',type=OpenApiTypes.DATE,location=OpenApiParameter.QUERY,description='Filter by release date',examples=[OpenApiExample('Example 1',summary='short optional summary',description='longer description',value='1993-08-23'),...],),],# override default docstring extractiondescription='More descriptive text',# provide Authentication class that deviates from the views defaultauth=None,# change the auto-generated operation nameoperation_id=None,# or even completely override what AutoSchema would generate. Provide raw Open API spec as Dict.operation=None,# attach request/response examples to the operation.examples=[OpenApiExample('Example 1',description='longer description',value=...),...],)deflist(self,request):# your non-standard behaviourreturnsuper().list(request)@extend_schema(request=AlbumLikeSerializer,responses={204:None},methods=["POST"])@extend_schema(description='Override a specific method',methods=["GET"])@action(detail=True,methods=['post','get'])defset_password(self,request,pk=None):# your action behaviour...More customizationStill not satisfied? You want more! We still got you covered.
Visitcustomizationfor more information.TestingInstall testing requirements.$pipinstall-rrequirements.txtRun with runtests.$./runtests.pyYou can also use the excellenttoxtesting tool to run the tests
against all supported versions of Python and Django. Install tox
globally, and then simply run:$tox