You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Cristi Vîjdea 0e62fd6f2b Update copyright year 1 year ago
.idea Fix lint errors 1 year ago
docs Add check to prevent build of docs with bad version 1 year ago
requirements Fix some version constraints 1 year ago
screenshots Add dcumentation (#12) 2 years ago
src/drf_yasg Fi doc typo (#286) 1 year ago
testproj Re-add test for DELETE form param 1 year ago
tests Re-add test for DELETE form param 1 year ago
.codecov.yml Prepare for 1.1.0 (#30) 2 years ago
.coveragerc Fix coverage problems 2 years ago
.editorconfig Add dcumentation (#12) 2 years ago
.gitattributes Update swagger-ui to 3.7.0 and add UI update script 2 years ago
.gitignore Fix docs build with sphinx 1.8 1 year ago
.readthedocs.yml Add .readthedocs.yml 1 year ago
.travis.yml Add check to prevent build of docs with bad version 1 year ago
CONTRIBUTING.rst Create testproj default user in data migration 1 year ago
LICENSE.rst Update copyright year 1 year ago Enable isolated_build for tox 1 year ago
Procfile Create testproj default user in data migration 1 year ago
README.rst Fix minor spelling typo (#282) 1 year ago
app.json Run testproj in a Heroku demo app (#38) 2 years ago
package-lock.json Update ReDoc to 2.0.0-rc.0 1 year ago
package.json Update ReDoc to 2.0.0-rc.0 1 year ago
pyproject.toml Fix some version constraints 1 year ago
requirements.txt Remove requirements/setup.txt and setup_requires 1 year ago
runtime.txt Update Heroku runtime to Python 3.7.1 1 year ago
setup.cfg Add LICENSE file to wheel 1 year ago Adjust dummy version 1 year ago
tox.ini Fix union types in sphinx docstrings 1 year ago Moar blocks 1 year ago


.. role:: python(code)
:language: python

drf-yasg - Yet another Swagger generator

|travis| |nbsp| |codecov| |nbsp| |rtd-badge| |nbsp| |pypi-version|

Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API.

Compatible with

- **Django Rest Framework**: 3.7.7, 3.8, 3.9
- **Django**: 1.11, 2.0, 2.1
- **Python**: 2.7, 3.4, 3.5, 3.6, 3.7

Only the latest patch version of each ``major.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 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.


* **Source**:
* **Documentation**:
* **Changelog**:
* **Live demo**:

.. image::
:alt: heroku deploy button


- 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 of
`swagger-ui <>`_ and
`redoc <>`_ for viewing the generated documentation
- schema view is cacheable out of the box
- generated Swagger schema can be automatically validated by
`swagger-spec-validator <>`_ or
`flex <>`_
- supports Django REST Framework API versioning with ``URLPathVersioning`` and ``NamespaceVersioning``; other DRF
or custom versioning schemes are not currently supported

.. figure::
:width: 100%
:figwidth: image
:alt: redoc screenshot

**Fully nested request and response schemas.**

.. figure::
:width: 100%
:figwidth: image
:alt: swagger-ui screenshot

**Choose between redoc and swagger-ui.**

.. figure::
:width: 100%
:figwidth: image
:alt: model definitions screenshot

**Real Model definitions.**

Table of contents

.. contents::
:depth: 4


0. Installation

The preferred instalation method is directly from pypi:

.. code:: console

pip install -U drf-yasg

Additionally, if you want to use the built-in validation mechanisms (see `4. Validation`_), you need to install
some extra requirements:

.. code:: console

pip install -U drf-yasg[validation]

.. _readme-quickstart:

1. Quickstart

In ````:

.. code:: python


In ````:

.. code:: python

from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi


schema_view = get_schema_view(
title="Snippets API",
description="Test description",
license=openapi.License(name="BSD License"),

urlpatterns = [
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^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/``

2. Configuration

a. ``get_schema_view`` parameters

- ``info`` - Swagger API Info object; if omitted, defaults to ``DEFAULT_INFO``
- ``url`` - API base url; if left blank will be deduced from the location the view is served at
- ``patterns`` - passed to SchemaGenerator
- ``urlconf`` - passed to SchemaGenerator
- ``public`` - if False, includes only endpoints the current user has access to
- ``validators`` - a list of validator names to apply on the generated schema; allowed values are ``flex``, ``ssv``
- ``generator_class`` - schema generator class to use; should be a subclass of ``OpenAPISchemaGenerator``
- ``authentication_classes`` - authentication classes for the schema view itself
- ``permission_classes`` - permission classes for the schema view itself

b. ``SchemaView`` options

- :python:`SchemaView.with_ui(renderer, cache_timeout, cache_kwargs)` - get a view instance using the
specified UI renderer; one of ``swagger``, ``redoc``
- :python:`SchemaView.without_ui(cache_timeout, cache_kwargs)` - get a view instance with no UI renderer;
same as ``as_cached_view`` with no kwargs
- :python:`SchemaView.as_cached_view(cache_timeout, cache_kwargs, **initkwargs)` - same as ``as_view``,
but with optional caching
- you can, of course, call :python:`as_view` as usual

All of the first 3 methods take two optional arguments, ``cache_timeout`` and ``cache_kwargs``; if present,
these are passed on to Django’s :python:`cached_page` decorator in order to enable caching on the resulting view.
See `3. Caching`_.


Additionally, you can include some more settings in your ```` file.
See for details.

3. Caching

Since 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 the `cache_page <>`__
decorator, using the default Django cache backend, can be changed using the ``cache_kwargs`` argument
* HTTP caching of the response is blocked to avoid confusing situations caused by being shown stale schemas
* the cached schema varies on the ``Cookie`` and ``Authorization`` HTTP 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. Validation

Given 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 passing :python:`validators=['flex', 'ssv']` to ``get_schema_view``; if the generated
schema is not valid, a :python:`SwaggerValidationError` 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. To
ensure compatibility with code generation tools, it is recommended to also employ one or more of the following methods:

``swagger-ui`` validation badge


If your schema is publicly accessible, `swagger-ui` will automatically validate it against the official swagger
online 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 of
`swagger-validator <>`_ and set the `VALIDATOR_URL` accordingly:

.. code:: python

'VALIDATOR_URL': 'http://localhost:8189',

.. code:: console

$ docker run --name swagger-validator -d -p 8189:8080 --add-host test.local: swaggerapi/swagger-validator
$ curl http://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi

Using ``swagger-cli``

.. code:: console

$ npm install -g swagger-cli
$ swagger-cli validate http://test.local:8002/swagger.yaml
http://test.local:8002/swagger.yaml is valid

Manually on ` <>`__

Importing the generated spec into 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

5. Code generation

You can use the specification outputted by this library together with
`swagger-codegen <>`_ to generate client code in your language of choice:

.. code:: console

$ docker run --rm -v ${PWD}:/local swaggerapi/swagger-codegen-cli generate -i /local/tests/reference.yaml -l javascript -o /local/.codegen/js

See the github page linked above for more details.

.. _readme-testproj:

6. Example project

For additional usage examples, you can take a look at the test project in the ``testproj`` directory:

.. code:: console

$ git clone
$ cd drf-yasg
$ virtualenv venv
$ source venv/bin/activate
(venv) $ cd testproj
(venv) $ python -m pip install -U pip setuptools
(venv) $ pip install -U -r requirements.txt
(venv) $ python migrate
(venv) $ python runserver
(venv) $ firefox localhost:8000/swagger/


``OpenAPI 2.0``/``Swagger`` is a format designed to encode information about a Web API into an easily parsable schema
that can then be used for rendering documentation, generating code, etc.

More details are available on ` <>`__ and on the `OpenAPI 2.0 specification
page <>`__.

From here on, the terms “OpenAPI” and “Swagger” are used interchangeably.

Swagger in Django Rest Framework

Since Django Rest Framework 3.7, there is now `built in support <>`__
for automatic OpenAPI 2.0 schema generation. However, this generation is based on the `coreapi <>`__
standard, which for the moment is vastly inferior to OpenAPI in both features and tooling support. In particular,
the OpenAPI codec/compatibility layer provided has a few major problems:

* there is no support for documenting response schemas and status codes
* nested schemas do not work properly
* does not handle more complex fields such as ``FileField``, ``ChoiceField``, …

In short this makes the generated schema unusable for code generation, and mediocre at best for documentation.

Other libraries

There are currently two decent Swagger schema generators that I could find for django-rest-framework:

* `django-rest-swagger <>`__
* `drf-openapi <>`__

``django-rest-swagger`` is just a wrapper around DRF 3.7 schema generation with an added UI, and
thus presents the same problems, while also being unmaintained. ``drf-openapi`` was
`discontinued by the author <>`_
on April 3rd, 2018.

Third-party integrations


Integration with `djangorestframework-camel-case <>`_ is
provided out of the box - if you have ``djangorestframework-camel-case`` installed and your ``APIView`` uses
``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer``, all property names will be converted to *camelCase* by default.


Integration with `djangorestframework-recursive <>`_ is
provided out of the box - if you have ``djangorestframework-recursive`` installed.

.. |travis| image::
:alt: Travis CI

.. |codecov| image::
:alt: Codecov

.. |pypi-version| image::
:alt: PyPI

.. |rtd-badge| image::
:alt: ReadTheDocs

.. |nbsp| unicode:: 0xA0