Package: djrf-yasg
GeneraterealSwagger/OpenAPI 2.0 specifications from a Django Rest Framework API.Compatible withDjango Rest Framework: 3.10, 3.11, 3.12, 3.13, 3.14Django: 2.2, 3.0, 3.1, 3.2, 4.0, 4.1Python: 3.6, 3.7, 3.8, 3.9, 3.10, 3.11Only the latest patch version of eachmajor.minorseries of Python, Django and Django REST Framework is supported.Only the latest version of drf-yasg is supported.Support of old versions is dropped immediately with the release
of a new version. Please do not create issues before upgrading to the latest release available at the time. Regression
reports are accepted and will be resolved with a new release as quickly as possible. Removed features will usually go
through a deprecation cycle of a few minor releases.Resources:Source:https://github.com/axnsan12/drf-yasg/Documentation:https://drf-yasg.readthedocs.io/Changelog:https://drf-yasg.readthedocs.io/en/stable/changelog.htmlLive demo:https://drf-yasg-demo.herokuapp.com/OpenAPI 3.0 noteIf you are looking to add Swagger/OpenAPI support to a new project you might want to take a look atdrf-spectacular, which is an actively maintained new library that
shares most of the goals of this project, while working with OpenAPI 3.0 schemas.OpenAPI 3.0 provides a lot more flexibility than 2.0 in the types of API that can be described.drf-yasgis unlikely to soon, if ever, get support for OpenAPI 3.0.Featuresfull support for nested Serializers and Schemasresponse schemas and descriptionsmodel definitions compatible with codegen toolscustomization hooks at all points in the spec generation processJSON and YAML format for specbundles latest version ofswagger-uiandredocfor viewing the generated documentationschema view is cacheable out of the boxgenerated Swagger schema can be automatically validated byswagger-spec-validatorsupports Django REST Framework API versioning withURLPathVersioningandNamespaceVersioning; other DRF
or custom versioning schemes are not currently supportedFully nested request and response schemas.Choose between redoc and swagger-ui.Real Model definitions.Table of contentsContentsOpenAPI 3.0 noteFeaturesTable of contentsUsage0. Installation1. Quickstart2. Configurationa.get_schema_viewparametersb.SchemaViewoptionsc.SWAGGER_SETTINGSandREDOC_SETTINGS3. Caching4. Validationswagger-uivalidation badgeOnlineOfflineUsingswagger-cliManually on editor.swagger.io5. Code generation6. Example projectThird-party integrationsdjangorestframework-camel-casedjangorestframework-recursivedrf-extra-fieldsUsage0. InstallationThe preferred installation method is directly from pypi:pip install -U drf-yasgAdditionally, if you want to use the built-in validation mechanisms (see4. Validation), you need to install
some extra requirements:pip install -U drf-yasg[validation]1. QuickstartInsettings.py:INSTALLED_APPS=[...'django.contrib.staticfiles',# required for serving swagger ui's css/js files'drf_yasg',...]Inurls.py:...fromdjango.urlsimportre_pathfromrest_frameworkimportpermissionsfromdrf_yasg.viewsimportget_schema_viewfromdrf_yasgimportopenapi...schema_view=get_schema_view(openapi.Info(title="Snippets API",default_version='v1',description="Test description",terms_of_service="https://www.google.com/policies/terms/",contact=openapi.Contact(email="contact@snippets.local"),license=openapi.License(name="BSD License"),),public=True,permission_classes=(permissions.AllowAny,),)urlpatterns=[path('swagger<format>/',schema_view.without_ui(cache_timeout=0),name='schema-json'),path('swagger/',schema_view.with_ui('swagger',cache_timeout=0),name='schema-swagger-ui'),path('redoc/',schema_view.with_ui('redoc',cache_timeout=0),name='schema-redoc'),...]This exposes 4 endpoints:A JSON view of your API specification at/swagger.jsonA YAML view of your API specification at/swagger.yamlA swagger-ui view of your API specification at/swagger/A ReDoc view of your API specification at/redoc/2. Configurationa.get_schema_viewparametersinfo- Swagger API Info object; if omitted, defaults toDEFAULT_INFOurl- API base url; if left blank will be deduced from the location the view is served atpatterns- passed to SchemaGeneratorurlconf- passed to SchemaGeneratorpublic- if False, includes only endpoints the current user has access tovalidators- a list of validator names to apply on the generated schema; onlyssvis currently supportedgenerator_class- schema generator class to use; should be a subclass ofOpenAPISchemaGeneratorauthentication_classes- authentication classes for the schema view itselfpermission_classes- permission classes for the schema view itselfb.SchemaViewoptionsSchemaView.with_ui(renderer,cache_timeout,cache_kwargs)- get a view instance using the
specified UI renderer; one ofswagger,redocSchemaView.without_ui(cache_timeout,cache_kwargs)- get a view instance with no UI renderer;
same asas_cached_viewwith no kwargsSchemaView.as_cached_view(cache_timeout,cache_kwargs,**initkwargs)- same asas_view,
but with optional cachingyou can, of course, callas_viewas usualAll of the first 3 methods take two optional arguments,cache_timeoutandcache_kwargs; if present,
these are passed on to Django’scached_pagedecorator in order to enable caching on the resulting view.
See3. Caching.c.SWAGGER_SETTINGSandREDOC_SETTINGSAdditionally, you can include some more settings in yoursettings.pyfile.
Seehttps://drf-yasg.readthedocs.io/en/stable/settings.htmlfor details.3. CachingSince the schema does not usually change during the lifetime of the django process, there is out of the box support for
caching the schema view in-memory, with some sane defaults:caching is enabled by thecache_pagedecorator, using the default Django cache backend, can be changed using thecache_kwargsargumentHTTP caching of the response is blocked to avoid confusing situations caused by being shown stale schemasthe cached schema varies on theCookieandAuthorizationHTTP headers to enable filtering of visible endpoints
according to the authentication credentials of each user; note that this means that every user accessing the schema
will have a separate schema cached in memory.4. ValidationGiven the numerous methods to manually customize the generated schema, it makes sense to validate the result to ensure
it still conforms to OpenAPI 2.0. To this end, validation is provided at the generation point using python swagger
libraries, and can be activated by passingvalidators=['ssv']toget_schema_view; if the generated
schema is not valid, aSwaggerValidationErroris raised by the handling codec.Warning:This internal validation can slow down your server.
Caching can mitigate the speed impact of validation.The provided validation will catch syntactic errors, but more subtle violations of the spec might slip by them. To
ensure compatibility with code generation tools, it is recommended to also employ one or more of the following methods:swagger-uivalidation badgeOnlineIf your schema is publicly accessible,swagger-uiwill automatically validate it against the official swagger
online validator and display the result in the bottom-right validation badge.OfflineIf your schema is not accessible from the internet, you can run a local copy ofswagger-validatorand set theVALIDATOR_URLaccordingly:SWAGGER_SETTINGS={...'VALIDATOR_URL':'http://localhost:8189',...}$dockerrun--nameswagger-validator-d-p8189:8080--add-hosttest.local:10.0.75.1swaggerapi/swagger-validator84dabd52ba967c32ae6b660934fa6a429ca6bc9e594d56e822a858b57039c8a2$curlhttp://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi{}Usingswagger-clihttps://www.npmjs.com/package/swagger-cli$npminstall-gswagger-cli[...]$swagger-clivalidatehttp://test.local:8002/swagger.yamlhttp://test.local:8002/swagger.yaml is validManually oneditor.swagger.ioImporting the generated spec intohttps://editor.swagger.io/will automatically trigger validation on it.
This method is currently the only way to get both syntactic and semantic validation on your specification.
The other validators only provide JSON schema-level validation, but miss things like duplicate operation names,
improper content types, etc5. Code generationYou can use the specification outputted by this library together withswagger-codegento generate client code in your language of choice:$dockerrun--rm-v${PWD}:/localswaggerapi/swagger-codegen-cligenerate-i/local/tests/reference.yaml-ljavascript-o/local/.codegen/jsSee the github page linked above for more details.6. Example projectFor additional usage examples, you can take a look at the test project in thetestprojdirectory:$gitclonehttps://github.com/axnsan12/drf-yasg.git$cddrf-yasg$virtualenvvenv$sourcevenv/bin/activate(venv)$cdtestproj(venv)$python-mpipinstall-Upipsetuptools(venv)$pipinstall-U-rrequirements.txt(venv)$pythonmanage.pymigrate(venv)$pythonmanage.pyrunserver(venv)$firefoxlocalhost:8000/swagger/Third-party integrationsdjangorestframework-camel-caseIntegration withdjangorestframework-camel-caseis
provided out of the box - if you havedjangorestframework-camel-caseinstalled and yourAPIViewusesCamelCaseJSONParserorCamelCaseJSONRenderer, all property names will be converted tocamelCaseby default.djangorestframework-recursiveIntegration withdjangorestframework-recursiveis
provided out of the box - if you havedjangorestframework-recursiveinstalled.drf-extra-fieldsIntegration withdrf-extra-fieldshas a problem with Base64 fields.
The drf-yasg will generate Base64 file or image fields as Readonly and not required. Here is a workaround code
for display the Base64 fields correctly.classPDFBase64FileField(Base64FileField):ALLOWED_TYPES=['pdf']classMeta:swagger_schema_fields={'type':'string','title':'File Content','description':'Content of the file base64 encoded','read_only':False# <-- FIX}defget_file_extension(self,filename,decoded_file):try:PyPDF2.PdfFileReader(io.BytesIO(decoded_file))exceptPyPDF2.utils.PdfReadErrorase:logger.warning(e)else:return'pdf'