- Notifications
You must be signed in to change notification settings - Fork438
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.
License
axnsan12/drf-yasg
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Generatereal Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API.
Compatible with
- Django Rest Framework: 3.13, 3.14, 3.15
- Django: 4.0, 4.1, 4.2, 5.0, 5.1, 5.2
- Python: 3.9, 3.10, 3.11, 3.12, 3.13
Only the latest patch version of eachmajor.minor series 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 releaseof a new version. Please do not create issues before upgrading to the latest release available at the time. Regressionreports are accepted and will be resolved with a new release as quickly as possible. Removed features will usually gothrough a deprecation cycle of a few minor releases.
Resources:
If 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 thatshares 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-yasg is unlikely to soon, if ever, get support for OpenAPI 3.0.
- full support for nested Serializers and Schemas
- response schemas and descriptions
- model definitions compatible with codegen tools
- customization hooks at all points in the spec generation process
- JSON and YAML format for spec
- bundles latest version ofswagger-ui andredoc for viewing the generated documentation
- schema view is cacheable out of the box
- generated Swagger schema can be automatically validated byswagger-spec-validator
- supports Django REST Framework API versioning with
URLPathVersioningandNamespaceVersioning; other DRFor custom versioning schemes are not currently supported
The preferred installation method is directly from pypi:
pip install --upgrade drf-yasgAdditionally, if you want to use the built-in validation mechanisms (see4. Validation), you need to installsome extra requirements:
pip install --upgrade drf-yasg[validation]Insettings.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.json - A YAML view of your API specification at
/swagger.yaml - A swagger-ui view of your API specification at
/swagger/ - A ReDoc view of your API specification at
/redoc/
info- 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 itself
SchemaView.with_ui(renderer, cache_timeout, cache_kwargs)- get a view instance using thespecified 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 caching- you can, of course, call
as_viewas usual
All of the first 3 methods take two optional arguments,cache_timeout andcache_kwargs; if present,these are passed on to Django’scached_page decorator in order to enable caching on the resulting view.See3. Caching.
Additionally, you can include some more settings in yoursettings.py file.Seehttps://drf-yasg.readthedocs.io/en/stable/settings.html for details.
Since the schema does not usually change during the lifetime of the django process, there is out of the box support forcaching 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 the
cache_kwargsargument - HTTP caching of the response is blocked to avoid confusing situations caused by being shown stale schemas
- the cached schema varies on the
CookieandAuthorizationHTTP headers to enable filtering of visible endpointsaccording to the authentication credentials of each user; note that this means that every user accessing the schemawill have a separate schema cached in memory.
Given the numerous methods to manually customize the generated schema, it makes sense to validate the result to ensureit still conforms to OpenAPI 2.0. To this end, validation is provided at the generation point using python swaggerlibraries, and can be activated by passingvalidators=['ssv'] toget_schema_view; if the generatedschema is not valid, aSwaggerValidationError is 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. Toensure compatibility with code generation tools, it is recommended to also employ one or more of the following methods:
If your schema is publicly accessible, swagger-ui will automatically validate it against the official swaggeronline validator and display the result in the bottom-right validation badge.
If your schema is not accessible from the internet, you can run a local copy ofswagger-validator and set theVALIDATOR_URL accordingly:
SWAGGER_SETTINGS= { ...'VALIDATOR_URL':'http://localhost:8189', ...}
$docker run --name swagger-validator -d -p 8189:8080 --add-host test.local:10.0.75.1 swaggerapi/swagger-validator84dabd52ba967c32ae6b660934fa6a429ca6bc9e594d56e822a858b57039c8a2$curl http://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi{}
https://www.npmjs.com/package/swagger-cli
$npm install -g swagger-cli[...]$swagger-cli validate http://test.local:8002/swagger.yamlhttp://test.local:8002/swagger.yaml is valid
Manually oneditor.swagger.io
Importing 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, etc
You can use the specification outputted by this library together withswagger-codegen to generate client code in your language of choice:
$docker run --rm -v${PWD}:/local swaggerapi/swagger-codegen-cli generate -i /local/tests/reference.yaml -l javascript -o /local/.codegen/jsSee the GitHub page linked above for more details.
For additional usage examples, you can take a look at the test project in thetestproj directory:
$git clone https://github.com/axnsan12/drf-yasg.git$cd drf-yasg$virtualenv venv$source venv/bin/activate(venv) $ cd testproj(venv) $ python -m pip install --upgrade pip setuptools(venv) $ pip install --upgrade -r requirements.txt(venv) $ python manage.py migrate(venv) $ python manage.py runserver(venv) $ firefox localhost:8000/swagger/
Integration withdjangorestframework-camel-case isprovided out of the box - if you havedjangorestframework-camel-case installed and yourAPIView usesCamelCaseJSONParser orCamelCaseJSONRenderer, all property names will be converted tocamelCase by default.
Integration withdjangorestframework-recursive isprovided out of the box - if you havedjangorestframework-recursive installed.
Integration withdrf-extra-fields has a problem with Base64 fields.The drf-yasg will generate Base64 file or image fields as Readonly and not required. Here is a workaround codefor 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'
Seehttps://drf-yasg.readthedocs.io/en/stable/contributing.html for details.
This repository adheres to semantic versioning standards. For moreinformation on semantic versioning visitSemVer.
To keep our process simple we merge pull requests into the master branch we usegit tags for releases. We use labels to mark which issues are intended for eachversion. For example:
- New issues without a version are given a
triagelabel. - Issues are labeled
bug,enhancementorquestionto describe theircontent - Once given a version, an issue will either have an assignee or be given a
help wantedlabel - A question that hasn't been answered will be given an
unansweredlabel
About
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.



