Debian Codegraph @

docs/topics/documenting-your-api.md

raw
1 # Documenting your API
2
3 > A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state.
4 >
5 > — Roy Fielding, [REST APIs must be hypertext driven][cite]
6
7 REST framework provides a range of different choices for documenting your API. The following is a non-exhaustive list of some of the most popular options.
8
9 ## Third-party packages for OpenAPI support
10
11 REST framework recommends using third-party packages for generating and presenting OpenAPI schemas, as they provide more features and flexibility than the built-in (deprecated) implementation.
12
13 ### drf-spectacular
14
15 [drf-spectacular][drf-spectacular] is an [OpenAPI 3][open-api] schema generation library with explicit
16 focus on extensibility, customizability and client generation. It is the recommended way for
17 generating and presenting OpenAPI schemas.
18
19 The library aims to extract as much schema information as possible, while providing decorators and extensions for easy
20 customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
21 i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
22 documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
23
24 ### drf-yasg
25
26 [drf-yasg][drf-yasg] is a [Swagger / OpenAPI 2][swagger] generation tool implemented without using the schema generation provided
27 by Django Rest Framework.
28
29 It aims to implement as much of the [OpenAPI 2][open-api] specification as possible - nested schemas, named models,
30 response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
31 generation tools like `swagger-codegen`.
32
33 This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
34
35 ![Screenshot - drf-yasg][image-drf-yasg]
36
37 ---
38
39 ## Built-in OpenAPI schema generation (deprecated)
40
41 !!! warning
42 **Deprecation notice:** REST framework's built-in support for generating OpenAPI schemas is deprecated in favor of third-party packages that provide this functionality instead. As a replacement, we recommend using **drf-spectacular**.
43
44
45 There are a number of packages available that allow you to generate HTML
46 documentation pages from OpenAPI schemas.
47
48 Two popular options are [Swagger UI][swagger-ui] and [ReDoc][redoc].
49
50 Both require little more than the location of your static schema file or
51 dynamic `SchemaView` endpoint.
52
53 ### A minimal example with Swagger UI
54
55 Assuming you've followed the example from the schemas documentation for routing
56 a dynamic `SchemaView`, a minimal Django template for using Swagger UI might be
57 this:
58
59 ```html
60 <!DOCTYPE html>
61 <html>
62 <head>
63 <title>Swagger</title>
64 <meta charset="utf-8"/>
65 <meta name="viewport" content="width=device-width, initial-scale=1">
66 <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" />
67 </head>
68 <body>
69 <div id="swagger-ui"></div>
70 <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
71 <script>
72 const ui = SwaggerUIBundle({
73 url: "{% url schema_url %}",
74 dom_id: '#swagger-ui',
75 presets: [
76 SwaggerUIBundle.presets.apis,
77 SwaggerUIBundle.SwaggerUIStandalonePreset
78 ],
79 layout: "BaseLayout",
80 requestInterceptor: (request) => {
81 request.headers['X-CSRFToken'] = "{{ csrf_token }}"
82 return request;
83 }
84 })
85 </script>
86 </body>
87 </html>
88 ```
89
90 Save this in your templates folder as `swagger-ui.html`. Then route a
91 `TemplateView` in your project's URL conf:
92
93 ```python
94 from django.views.generic import TemplateView
95
96 urlpatterns = [
97 # ...
98 # Route TemplateView to serve Swagger UI template.
99 # * Provide `extra_context` with view name of `SchemaView`.
100 path(
101 "swagger-ui/",
102 TemplateView.as_view(
103 template_name="swagger-ui.html",
104 extra_context={"schema_url": "openapi-schema"},
105 ),
106 name="swagger-ui",
107 ),
108 ]
109 ```
110
111 See the [Swagger UI documentation][swagger-ui] for advanced usage.
112
113 ### A minimal example with ReDoc.
114
115 Assuming you've followed the example from the schemas documentation for routing
116 a dynamic `SchemaView`, a minimal Django template for using ReDoc might be
117 this:
118
119 ```html
120 <!DOCTYPE html>
121 <html>
122 <head>
123 <title>ReDoc</title>
124 <!-- needed for adaptive design -->
125 <meta charset="utf-8"/>
126 <meta name="viewport" content="width=device-width, initial-scale=1">
127 <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
128 <!-- ReDoc doesn't change outer page styles -->
129 <style>
130 body {
131 margin: 0;
132 padding: 0;
133 }
134 </style>
135 </head>
136 <body>
137 <redoc spec-url='{% url schema_url %}'></redoc>
138 <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"> </script>
139 </body>
140 </html>
141 ```
142
143 Save this in your templates folder as `redoc.html`. Then route a `TemplateView`
144 in your project's URL conf:
145
146 ```python
147 from django.views.generic import TemplateView
148
149 urlpatterns = [
150 # ...
151 # Route TemplateView to serve the ReDoc template.
152 # * Provide `extra_context` with view name of `SchemaView`.
153 path(
154 "redoc/",
155 TemplateView.as_view(
156 template_name="redoc.html", extra_context={"schema_url": "openapi-schema"}
157 ),
158 name="redoc",
159 ),
160 ]
161 ```
162
163 See the [ReDoc documentation][redoc] for advanced usage.
164
165
166 ## Self describing APIs
167
168 The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser.
169
170 ![Screenshot - Self describing API][image-self-describing-api]
171
172 ---
173
174 #### Setting the title
175
176 The title that is used in the browsable API is generated from the view class name or function name. Any trailing `View` or `ViewSet` suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores.
177
178 For example, the view `UserListView`, will be named `User List` when presented in the browsable API.
179
180 When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set `UserViewSet` will generate views named `User List` and `User Instance`.
181
182 #### Setting the description
183
184 The description in the browsable API is generated from the docstring of the view or viewset.
185
186 If the python `Markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example:
187
188 class AccountListView(views.APIView):
189 """
190 Returns a list of all **active** accounts in the system.
191
192 For more details on how accounts are activated please [see here][ref].
193
194 [ref]: http://example.com/activating-accounts
195 """
196
197 Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the list and retrieve views, use docstring sections as described in [Schemas as documentation: Examples][schemas-examples].
198
199 #### The `OPTIONS` method
200
201 REST framework APIs also support programmatically accessible descriptions, using the `OPTIONS` HTTP method. A view will respond to an `OPTIONS` request with metadata including the name, description, and the various media types it accepts and responds with.
202
203 When using the generic views, any `OPTIONS` requests will additionally respond with metadata regarding any `POST` or `PUT` actions available, describing which fields are on the serializer.
204
205 You can modify the response behavior to `OPTIONS` requests by overriding the `options` view method and/or by providing a custom Metadata class. For example:
206
207 def options(self, request, *args, **kwargs):
208 """
209 Don't include the view description in OPTIONS responses.
210 """
211 meta = self.metadata_class()
212 data = meta.determine_metadata(request, self)
213 data.pop('description')
214 return Response(data=data, status=status.HTTP_200_OK)
215
216 See [the Metadata docs][metadata-docs] for more details.
217
218 ---
219
220 ## The hypermedia approach
221
222 To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.
223
224 In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the *media types* that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document.
225
226 To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.
227
228 [cite]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
229
230 [hypermedia-docs]: rest-hypermedia-hateoas.md
231 [metadata-docs]: ../api-guide/metadata.md
232 [schemas-examples]: ../api-guide/schemas.md#examples
233
234 [image-drf-yasg]: ../img/drf-yasg.png
235 [image-self-describing-api]: ../img/self-describing.png
236
237 [drf-yasg]: https://github.com/axnsan12/drf-yasg/
238 [drf-spectacular]: https://github.com/tfranzel/drf-spectacular/
239 [markdown]: https://daringfireball.net/projects/markdown/syntax
240 [open-api]: https://openapis.org/
241 [redoc]: https://github.com/Rebilly/ReDoc
242 [swagger]: https://swagger.io/
243 [swagger-ui]: https://swagger.io/tools/swagger-ui/