| 1 |
.. role:: python(code) |
| 2 |
:language: python |
| 3 |
|
| 4 |
######################################## |
| 5 |
drf-yasg - Yet another Swagger generator |
| 6 |
######################################## |
| 7 |
|
| 8 |
Generate **real** Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. |
| 9 |
|
| 10 |
Compatible with |
| 11 |
|
| 12 |
- **Django Rest Framework**: 3.13, 3.14, 3.15 |
| 13 |
- **Django**: 4.0, 4.1, 4.2, 5.0, 5.1, 5.2 |
| 14 |
- **Python**: 3.9, 3.10, 3.11, 3.12, 3.13 |
| 15 |
|
| 16 |
Only the latest patch version of each ``major.minor`` series of Python, Django and Django REST Framework is supported. |
| 17 |
|
| 18 |
**Only the latest version of drf-yasg is supported.** Support of old versions is dropped immediately with the release |
| 19 |
of a new version. Please do not create issues before upgrading to the latest release available at the time. Regression |
| 20 |
reports are accepted and will be resolved with a new release as quickly as possible. Removed features will usually go |
| 21 |
through a deprecation cycle of a few minor releases. |
| 22 |
|
| 23 |
Resources: |
| 24 |
|
| 25 |
* `Sources <https://github.com/axnsan12/drf-yasg>`_ |
| 26 |
* `Documentation <https://drf-yasg.readthedocs.io>`_ |
| 27 |
* `Changelog <https://drf-yasg.readthedocs.io/en/stable/changelog.html>`_ |
| 28 |
* `Discussion <https://app.gitter.im/#/room/#drf-yasg:gitter.im>`_ |
| 29 |
|
| 30 |
**************** |
| 31 |
OpenAPI 3.0 note |
| 32 |
**************** |
| 33 |
|
| 34 |
If you are looking to add Swagger/OpenAPI support to a new project you might want to take a look at |
| 35 |
`drf-spectacular <https://github.com/tfranzel/drf-spectacular>`_, which is an actively maintained new library that |
| 36 |
shares most of the goals of this project, while working with OpenAPI 3.0 schemas. |
| 37 |
|
| 38 |
OpenAPI 3.0 provides a lot more flexibility than 2.0 in the types of API that can be described. |
| 39 |
``drf-yasg`` is unlikely to soon, if ever, get support for OpenAPI 3.0. |
| 40 |
|
| 41 |
|
| 42 |
******** |
| 43 |
Features |
| 44 |
******** |
| 45 |
|
| 46 |
- full support for nested Serializers and Schemas |
| 47 |
- response schemas and descriptions |
| 48 |
- model definitions compatible with codegen tools |
| 49 |
- customization hooks at all points in the spec generation process |
| 50 |
- JSON and YAML format for spec |
| 51 |
- bundles latest version of |
| 52 |
`swagger-ui <https://github.com/swagger-api/swagger-ui>`_ and |
| 53 |
`redoc <https://github.com/Rebilly/ReDoc>`_ for viewing the generated documentation |
| 54 |
- schema view is cacheable out of the box |
| 55 |
- generated Swagger schema can be automatically validated by |
| 56 |
`swagger-spec-validator <https://github.com/Yelp/swagger_spec_validator>`_ |
| 57 |
- supports Django REST Framework API versioning with ``URLPathVersioning`` and ``NamespaceVersioning``; other DRF |
| 58 |
or custom versioning schemes are not currently supported |
| 59 |
|
| 60 |
.. figure:: https://raw.githubusercontent.com/axnsan12/drf-yasg/1.0.2/screenshots/redoc-nested-response.png |
| 61 |
:width: 100% |
| 62 |
:figwidth: image |
| 63 |
:alt: redoc screenshot |
| 64 |
|
| 65 |
**Fully nested request and response schemas.** |
| 66 |
|
| 67 |
.. figure:: https://raw.githubusercontent.com/axnsan12/drf-yasg/1.0.2/screenshots/swagger-ui-list.png |
| 68 |
:width: 100% |
| 69 |
:figwidth: image |
| 70 |
:alt: swagger-ui screenshot |
| 71 |
|
| 72 |
**Choose between redoc and swagger-ui.** |
| 73 |
|
| 74 |
.. figure:: https://raw.githubusercontent.com/axnsan12/drf-yasg/1.0.2/screenshots/swagger-ui-models.png |
| 75 |
:width: 100% |
| 76 |
:figwidth: image |
| 77 |
:alt: model definitions screenshot |
| 78 |
|
| 79 |
**Real Model definitions.** |
| 80 |
|
| 81 |
|
| 82 |
***************** |
| 83 |
Table of contents |
| 84 |
***************** |
| 85 |
|
| 86 |
.. contents:: |
| 87 |
:depth: 4 |
| 88 |
|
| 89 |
***** |
| 90 |
Usage |
| 91 |
***** |
| 92 |
|
| 93 |
0. Installation |
| 94 |
=============== |
| 95 |
|
| 96 |
The preferred installation method is directly from pypi: |
| 97 |
|
| 98 |
.. code:: console |
| 99 |
|
| 100 |
pip install --upgrade drf-yasg |
| 101 |
|
| 102 |
Additionally, if you want to use the built-in validation mechanisms (see `4. Validation`_), you need to install |
| 103 |
some extra requirements: |
| 104 |
|
| 105 |
.. code:: console |
| 106 |
|
| 107 |
pip install --upgrade drf-yasg[validation] |
| 108 |
|
| 109 |
.. _readme-quickstart: |
| 110 |
|
| 111 |
1. Quickstart |
| 112 |
============= |
| 113 |
|
| 114 |
In ``settings.py``: |
| 115 |
|
| 116 |
.. code:: python |
| 117 |
|
| 118 |
INSTALLED_APPS = [ |
| 119 |
... |
| 120 |
'django.contrib.staticfiles', # required for serving swagger ui's css/js files |
| 121 |
'drf_yasg', |
| 122 |
... |
| 123 |
] |
| 124 |
|
| 125 |
In ``urls.py``: |
| 126 |
|
| 127 |
.. code:: python |
| 128 |
|
| 129 |
... |
| 130 |
from django.urls import re_path |
| 131 |
from rest_framework import permissions |
| 132 |
from drf_yasg.views import get_schema_view |
| 133 |
from drf_yasg import openapi |
| 134 |
|
| 135 |
... |
| 136 |
|
| 137 |
schema_view = get_schema_view( |
| 138 |
openapi.Info( |
| 139 |
title="Snippets API", |
| 140 |
default_version='v1', |
| 141 |
description="Test description", |
| 142 |
terms_of_service="https://www.google.com/policies/terms/", |
| 143 |
contact=openapi.Contact(email="[email protected]"), |
| 144 |
license=openapi.License(name="BSD License"), |
| 145 |
), |
| 146 |
public=True, |
| 147 |
permission_classes=(permissions.AllowAny,), |
| 148 |
) |
| 149 |
|
| 150 |
urlpatterns = [ |
| 151 |
path('swagger.<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'), |
| 152 |
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), |
| 153 |
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), |
| 154 |
... |
| 155 |
] |
| 156 |
|
| 157 |
This exposes 4 endpoints: |
| 158 |
|
| 159 |
* A JSON view of your API specification at ``/swagger.json`` |
| 160 |
* A YAML view of your API specification at ``/swagger.yaml`` |
| 161 |
* A swagger-ui view of your API specification at ``/swagger/`` |
| 162 |
* A ReDoc view of your API specification at ``/redoc/`` |
| 163 |
|
| 164 |
2. Configuration |
| 165 |
================ |
| 166 |
|
| 167 |
--------------------------------- |
| 168 |
a. ``get_schema_view`` parameters |
| 169 |
--------------------------------- |
| 170 |
|
| 171 |
- ``info`` - Swagger API Info object; if omitted, defaults to ``DEFAULT_INFO`` |
| 172 |
- ``url`` - API base url; if left blank will be deduced from the location the view is served at |
| 173 |
- ``patterns`` - passed to SchemaGenerator |
| 174 |
- ``urlconf`` - passed to SchemaGenerator |
| 175 |
- ``public`` - if False, includes only endpoints the current user has access to |
| 176 |
- ``validators`` - a list of validator names to apply on the generated schema; only ``ssv`` is currently supported |
| 177 |
- ``generator_class`` - schema generator class to use; should be a subclass of ``OpenAPISchemaGenerator`` |
| 178 |
- ``authentication_classes`` - authentication classes for the schema view itself |
| 179 |
- ``permission_classes`` - permission classes for the schema view itself |
| 180 |
|
| 181 |
------------------------------- |
| 182 |
b. ``SchemaView`` options |
| 183 |
------------------------------- |
| 184 |
|
| 185 |
- :python:`SchemaView.with_ui(renderer, cache_timeout, cache_kwargs)` - get a view instance using the |
| 186 |
specified UI renderer; one of ``swagger``, ``redoc`` |
| 187 |
- :python:`SchemaView.without_ui(cache_timeout, cache_kwargs)` - get a view instance with no UI renderer; |
| 188 |
same as ``as_cached_view`` with no kwargs |
| 189 |
- :python:`SchemaView.as_cached_view(cache_timeout, cache_kwargs, **initkwargs)` - same as ``as_view``, |
| 190 |
but with optional caching |
| 191 |
- you can, of course, call :python:`as_view` as usual |
| 192 |
|
| 193 |
All of the first 3 methods take two optional arguments, ``cache_timeout`` and ``cache_kwargs``; if present, |
| 194 |
these are passed on to Django’s :python:`cached_page` decorator in order to enable caching on the resulting view. |
| 195 |
See `3. Caching`_. |
| 196 |
|
| 197 |
---------------------------------------------- |
| 198 |
c. ``SWAGGER_SETTINGS`` and ``REDOC_SETTINGS`` |
| 199 |
---------------------------------------------- |
| 200 |
|
| 201 |
Additionally, you can include some more settings in your ``settings.py`` file. |
| 202 |
See https://drf-yasg.readthedocs.io/en/stable/settings.html for details. |
| 203 |
|
| 204 |
|
| 205 |
3. Caching |
| 206 |
========== |
| 207 |
|
| 208 |
Since the schema does not usually change during the lifetime of the django process, there is out of the box support for |
| 209 |
caching the schema view in-memory, with some sane defaults: |
| 210 |
|
| 211 |
* caching is enabled by the `cache_page <https://docs.djangoproject.com/en/1.11/topics/cache/#the-per-view-cache>`__ |
| 212 |
decorator, using the default Django cache backend, can be changed using the ``cache_kwargs`` argument |
| 213 |
* HTTP caching of the response is blocked to avoid confusing situations caused by being shown stale schemas |
| 214 |
* the cached schema varies on the ``Cookie`` and ``Authorization`` HTTP headers to enable filtering of visible endpoints |
| 215 |
according to the authentication credentials of each user; note that this means that every user accessing the schema |
| 216 |
will have a separate schema cached in memory. |
| 217 |
|
| 218 |
4. Validation |
| 219 |
============= |
| 220 |
|
| 221 |
Given the numerous methods to manually customize the generated schema, it makes sense to validate the result to ensure |
| 222 |
it still conforms to OpenAPI 2.0. To this end, validation is provided at the generation point using python swagger |
| 223 |
libraries, and can be activated by passing :python:`validators=['ssv']` to ``get_schema_view``; if the generated |
| 224 |
schema is not valid, a :python:`SwaggerValidationError` is raised by the handling codec. |
| 225 |
|
| 226 |
**Warning:** This internal validation can slow down your server. |
| 227 |
Caching can mitigate the speed impact of validation. |
| 228 |
|
| 229 |
The provided validation will catch syntactic errors, but more subtle violations of the spec might slip by them. To |
| 230 |
ensure compatibility with code generation tools, it is recommended to also employ one or more of the following methods: |
| 231 |
|
| 232 |
------------------------------- |
| 233 |
``swagger-ui`` validation badge |
| 234 |
------------------------------- |
| 235 |
|
| 236 |
Online |
| 237 |
^^^^^^ |
| 238 |
|
| 239 |
If your schema is publicly accessible, `swagger-ui` will automatically validate it against the official swagger |
| 240 |
online validator and display the result in the bottom-right validation badge. |
| 241 |
|
| 242 |
Offline |
| 243 |
^^^^^^^ |
| 244 |
|
| 245 |
If your schema is not accessible from the internet, you can run a local copy of |
| 246 |
`swagger-validator <https://hub.docker.com/r/swaggerapi/swagger-validator/>`_ and set the ``VALIDATOR_URL`` accordingly: |
| 247 |
|
| 248 |
.. code:: python |
| 249 |
|
| 250 |
SWAGGER_SETTINGS = { |
| 251 |
... |
| 252 |
'VALIDATOR_URL': 'http://localhost:8189', |
| 253 |
... |
| 254 |
} |
| 255 |
|
| 256 |
.. code:: console |
| 257 |
|
| 258 |
$ docker run --name swagger-validator -d -p 8189:8080 --add-host test.local:10.0.75.1 swaggerapi/swagger-validator |
| 259 |
84dabd52ba967c32ae6b660934fa6a429ca6bc9e594d56e822a858b57039c8a2 |
| 260 |
$ curl http://localhost:8189/debug?url=http://test.local:8002/swagger/?format=openapi |
| 261 |
{} |
| 262 |
|
| 263 |
--------------------- |
| 264 |
Using ``swagger-cli`` |
| 265 |
--------------------- |
| 266 |
|
| 267 |
https://www.npmjs.com/package/swagger-cli |
| 268 |
|
| 269 |
.. code:: console |
| 270 |
|
| 271 |
$ npm install -g swagger-cli |
| 272 |
[...] |
| 273 |
$ swagger-cli validate http://test.local:8002/swagger.yaml |
| 274 |
http://test.local:8002/swagger.yaml is valid |
| 275 |
|
| 276 |
-------------------------------------------------------------- |
| 277 |
Manually on `editor.swagger.io <https://editor.swagger.io/>`__ |
| 278 |
-------------------------------------------------------------- |
| 279 |
|
| 280 |
Importing the generated spec into https://editor.swagger.io/ will automatically trigger validation on it. |
| 281 |
This method is currently the only way to get both syntactic and semantic validation on your specification. |
| 282 |
The other validators only provide JSON schema-level validation, but miss things like duplicate operation names, |
| 283 |
improper content types, etc |
| 284 |
|
| 285 |
5. Code generation |
| 286 |
================== |
| 287 |
|
| 288 |
You can use the specification outputted by this library together with |
| 289 |
`swagger-codegen <https://github.com/swagger-api/swagger-codegen>`_ to generate client code in your language of choice: |
| 290 |
|
| 291 |
.. code:: console |
| 292 |
|
| 293 |
$ docker run --rm -v ${PWD}:/local swaggerapi/swagger-codegen-cli generate -i /local/tests/reference.yaml -l javascript -o /local/.codegen/js |
| 294 |
|
| 295 |
See the GitHub page linked above for more details. |
| 296 |
|
| 297 |
.. _readme-testproj: |
| 298 |
|
| 299 |
6. Example project |
| 300 |
================== |
| 301 |
|
| 302 |
For additional usage examples, you can take a look at the test project in the ``testproj`` directory: |
| 303 |
|
| 304 |
.. code:: console |
| 305 |
|
| 306 |
$ git clone https://github.com/axnsan12/drf-yasg.git |
| 307 |
$ cd drf-yasg |
| 308 |
$ virtualenv venv |
| 309 |
$ source venv/bin/activate |
| 310 |
(venv) $ cd testproj |
| 311 |
(venv) $ python -m pip install --upgrade pip setuptools |
| 312 |
(venv) $ pip install --upgrade -r requirements.txt |
| 313 |
(venv) $ python manage.py migrate |
| 314 |
(venv) $ python manage.py runserver |
| 315 |
(venv) $ firefox localhost:8000/swagger/ |
| 316 |
|
| 317 |
************************ |
| 318 |
Third-party integrations |
| 319 |
************************ |
| 320 |
|
| 321 |
djangorestframework-camel-case |
| 322 |
=============================== |
| 323 |
|
| 324 |
Integration with `djangorestframework-camel-case <https://github.com/vbabiy/djangorestframework-camel-case>`_ is |
| 325 |
provided out of the box - if you have ``djangorestframework-camel-case`` installed and your ``APIView`` uses |
| 326 |
``CamelCaseJSONParser`` or ``CamelCaseJSONRenderer``, all property names will be converted to *camelCase* by default. |
| 327 |
|
| 328 |
djangorestframework-recursive |
| 329 |
=============================== |
| 330 |
|
| 331 |
Integration with `djangorestframework-recursive <https://github.com/heywbj/django-rest-framework-recursive>`_ is |
| 332 |
provided out of the box - if you have ``djangorestframework-recursive`` installed. |
| 333 |
|
| 334 |
drf-extra-fields |
| 335 |
================= |
| 336 |
|
| 337 |
Integration with `drf-extra-fields <https://github.com/Hipo/drf-extra-fields>`_ has a problem with Base64 fields. |
| 338 |
The drf-yasg will generate Base64 file or image fields as Readonly and not required. Here is a workaround code |
| 339 |
for display the Base64 fields correctly. |
| 340 |
|
| 341 |
.. code:: python |
| 342 |
|
| 343 |
class PDFBase64FileField(Base64FileField): |
| 344 |
ALLOWED_TYPES = ['pdf'] |
| 345 |
|
| 346 |
class Meta: |
| 347 |
swagger_schema_fields = { |
| 348 |
'type': 'string', |
| 349 |
'title': 'File Content', |
| 350 |
'description': 'Content of the file base64 encoded', |
| 351 |
'read_only': False # <-- FIX |
| 352 |
} |
| 353 |
|
| 354 |
def get_file_extension(self, filename, decoded_file): |
| 355 |
try: |
| 356 |
PyPDF2.PdfFileReader(io.BytesIO(decoded_file)) |
| 357 |
except PyPDF2.utils.PdfReadError as e: |
| 358 |
logger.warning(e) |
| 359 |
else: |
| 360 |
return 'pdf' |
| 361 |
|
| 362 |
************ |
| 363 |
Contributing |
| 364 |
************ |
| 365 |
|
| 366 |
See https://drf-yasg.readthedocs.io/en/stable/contributing.html for details. |
| 367 |
|
| 368 |
This repository adheres to semantic versioning standards. For more |
| 369 |
information on semantic versioning visit `SemVer <https://semver.org>`_. |
| 370 |
|
| 371 |
To keep our process simple we merge pull requests into the master branch we use |
| 372 |
git tags for releases. We use labels to mark which issues are intended for each |
| 373 |
version. For example: |
| 374 |
|
| 375 |
.. figure:: ./docs/images/flow.png |
| 376 |
:width: 70% |
| 377 |
:figwidth: image |
| 378 |
:alt: Git flow |
| 379 |
:align: center |
| 380 |
|
| 381 |
Labels |
| 382 |
====== |
| 383 |
|
| 384 |
- New issues without a version are given a ``triage`` label. |
| 385 |
|
| 386 |
- Issues are labeled ``bug``, ``enhancement`` or ``question`` to describe their |
| 387 |
content |
| 388 |
|
| 389 |
- Once given a version, an issue will either have an assignee or be given a |
| 390 |
``help wanted`` label |
| 391 |
|
| 392 |
- A question that hasn't been answered will be given an ``unanswered`` label |