Debian Codegraph @

README.rst

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