| 1 |
--- |
| 2 |
source: |
| 3 |
- schemas |
| 4 |
--- |
| 5 |
|
| 6 |
# Schema |
| 7 |
|
| 8 |
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support. |
| 9 |
> |
| 10 |
> — Heroku, [JSON Schema for the Heroku Platform API][cite] |
| 11 |
|
| 12 |
--- |
| 13 |
|
| 14 |
**Deprecation notice:** |
| 15 |
|
| 16 |
REST framework's built-in support for generating OpenAPI schemas is |
| 17 |
**deprecated** in favor of 3rd party packages that can provide this |
| 18 |
functionality instead. The built-in support will be moved into a separate |
| 19 |
package and then subsequently retired over the next releases. |
| 20 |
|
| 21 |
As a full-fledged replacement, we recommend the [drf-spectacular] package. |
| 22 |
It has extensive support for generating OpenAPI 3 schemas from |
| 23 |
REST framework APIs, with both automatic and customizable options available. |
| 24 |
For further information please refer to |
| 25 |
[Documenting your API](../topics/documenting-your-api.md#drf-spectacular). |
| 26 |
|
| 27 |
--- |
| 28 |
|
| 29 |
API schemas are a useful tool that allow for a range of use cases, including |
| 30 |
generating reference documentation, or driving dynamic client libraries that |
| 31 |
can interact with your API. |
| 32 |
|
| 33 |
Django REST Framework provides support for automatic generation of |
| 34 |
[OpenAPI][openapi] schemas. |
| 35 |
|
| 36 |
## Overview |
| 37 |
|
| 38 |
Schema generation has several moving parts. It's worth having an overview: |
| 39 |
|
| 40 |
* `SchemaGenerator` is a top-level class that is responsible for walking your |
| 41 |
configured URL patterns, finding `APIView` subclasses, enquiring for their |
| 42 |
schema representation, and compiling the final schema object. |
| 43 |
* `AutoSchema` encapsulates all the details necessary for per-view schema |
| 44 |
introspection. Is attached to each view via the `schema` attribute. You |
| 45 |
subclass `AutoSchema` in order to customize your schema. |
| 46 |
* The `generateschema` management command allows you to generate a static schema |
| 47 |
offline. |
| 48 |
* Alternatively, you can route `SchemaView` to dynamically generate and serve |
| 49 |
your schema. |
| 50 |
* `settings.DEFAULT_SCHEMA_CLASS` allows you to specify an `AutoSchema` |
| 51 |
subclass to serve as your project's default. |
| 52 |
|
| 53 |
The following sections explain more. |
| 54 |
|
| 55 |
## Generating an OpenAPI Schema |
| 56 |
|
| 57 |
### Install dependencies |
| 58 |
|
| 59 |
pip install pyyaml uritemplate inflection |
| 60 |
|
| 61 |
* `pyyaml` is used to generate schema into YAML-based OpenAPI format. |
| 62 |
* `uritemplate` is used internally to get parameters in path. |
| 63 |
* `inflection` is used to pluralize operations more appropriately in the list endpoints. |
| 64 |
|
| 65 |
### Generating a static schema with the `generateschema` management command |
| 66 |
|
| 67 |
If your schema is static, you can use the `generateschema` management command: |
| 68 |
|
| 69 |
```bash |
| 70 |
./manage.py generateschema --file openapi-schema.yml |
| 71 |
``` |
| 72 |
|
| 73 |
Once you've generated a schema in this way you can annotate it with any |
| 74 |
additional information that cannot be automatically inferred by the schema |
| 75 |
generator. |
| 76 |
|
| 77 |
You might want to check your API schema into version control and update it |
| 78 |
with each new release, or serve the API schema from your site's static media. |
| 79 |
|
| 80 |
### Generating a dynamic schema with `SchemaView` |
| 81 |
|
| 82 |
If you require a dynamic schema, because foreign key choices depend on database |
| 83 |
values, for example, you can route a `SchemaView` that will generate and serve |
| 84 |
your schema on demand. |
| 85 |
|
| 86 |
To route a `SchemaView`, use the `get_schema_view()` helper. |
| 87 |
|
| 88 |
In `urls.py`: |
| 89 |
|
| 90 |
```python |
| 91 |
from rest_framework.schemas import get_schema_view |
| 92 |
|
| 93 |
urlpatterns = [ |
| 94 |
# ... |
| 95 |
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs. |
| 96 |
# * `title` and `description` parameters are passed to `SchemaGenerator`. |
| 97 |
# * Provide view name for use with `reverse()`. |
| 98 |
path( |
| 99 |
"openapi", |
| 100 |
get_schema_view( |
| 101 |
title="Your Project", description="API for all things …", version="1.0.0" |
| 102 |
), |
| 103 |
name="openapi-schema", |
| 104 |
), |
| 105 |
# ... |
| 106 |
] |
| 107 |
``` |
| 108 |
|
| 109 |
#### `get_schema_view()` |
| 110 |
|
| 111 |
The `get_schema_view()` helper takes the following keyword arguments: |
| 112 |
|
| 113 |
* `title`: May be used to provide a descriptive title for the schema definition. |
| 114 |
* `description`: Longer descriptive text. |
| 115 |
* `version`: The version of the API. |
| 116 |
* `url`: May be used to pass a canonical base URL for the schema. |
| 117 |
|
| 118 |
schema_view = get_schema_view( |
| 119 |
title='Server Monitoring API', |
| 120 |
url='https://www.example.org/api/' |
| 121 |
) |
| 122 |
|
| 123 |
* `urlconf`: A string representing the import path to the URL conf that you want |
| 124 |
to generate an API schema for. This defaults to the value of Django's |
| 125 |
`ROOT_URLCONF` setting. |
| 126 |
|
| 127 |
schema_view = get_schema_view( |
| 128 |
title='Server Monitoring API', |
| 129 |
url='https://www.example.org/api/', |
| 130 |
urlconf='myproject.urls' |
| 131 |
) |
| 132 |
|
| 133 |
* `patterns`: List of url patterns to limit the schema introspection to. If you |
| 134 |
only want the `myproject.api` urls to be exposed in the schema: |
| 135 |
|
| 136 |
schema_url_patterns = [ |
| 137 |
path('api/', include('myproject.api.urls')), |
| 138 |
] |
| 139 |
|
| 140 |
schema_view = get_schema_view( |
| 141 |
title='Server Monitoring API', |
| 142 |
url='https://www.example.org/api/', |
| 143 |
patterns=schema_url_patterns, |
| 144 |
) |
| 145 |
* `public`: May be used to specify if schema should bypass views permissions. Default to False |
| 146 |
|
| 147 |
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be |
| 148 |
passed to the `SchemaView`. |
| 149 |
* `authentication_classes`: May be used to specify the list of authentication |
| 150 |
classes that will apply to the schema endpoint. Defaults to |
| 151 |
`settings.DEFAULT_AUTHENTICATION_CLASSES` |
| 152 |
* `permission_classes`: May be used to specify the list of permission classes |
| 153 |
that will apply to the schema endpoint. Defaults to |
| 154 |
`settings.DEFAULT_PERMISSION_CLASSES`. |
| 155 |
* `renderer_classes`: May be used to pass the set of renderer classes that can |
| 156 |
be used to render the API root endpoint. |
| 157 |
|
| 158 |
|
| 159 |
## SchemaGenerator |
| 160 |
|
| 161 |
**Schema-level customization** |
| 162 |
|
| 163 |
```python |
| 164 |
from rest_framework.schemas.openapi import SchemaGenerator |
| 165 |
``` |
| 166 |
|
| 167 |
`SchemaGenerator` is a class that walks a list of routed URL patterns, requests |
| 168 |
the schema for each view and collates the resulting OpenAPI schema. |
| 169 |
|
| 170 |
Typically you won't need to instantiate `SchemaGenerator` yourself, but you can |
| 171 |
do so like so: |
| 172 |
|
| 173 |
generator = SchemaGenerator(title='Stock Prices API') |
| 174 |
|
| 175 |
Arguments: |
| 176 |
|
| 177 |
* `title` **required**: The name of the API. |
| 178 |
* `description`: Longer descriptive text. |
| 179 |
* `version`: The version of the API. Defaults to `0.1.0`. |
| 180 |
* `url`: The root URL of the API schema. This option is not required unless the schema is included under path prefix. |
| 181 |
* `patterns`: A list of URLs to inspect when generating the schema. Defaults to the project's URL conf. |
| 182 |
* `urlconf`: A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`. |
| 183 |
|
| 184 |
In order to customize the top-level schema, subclass |
| 185 |
`rest_framework.schemas.openapi.SchemaGenerator` and provide your subclass |
| 186 |
as an argument to the `generateschema` command or `get_schema_view()` helper |
| 187 |
function. |
| 188 |
|
| 189 |
### get_schema(self, request=None, public=False) |
| 190 |
|
| 191 |
Returns a dictionary that represents the OpenAPI schema: |
| 192 |
|
| 193 |
generator = SchemaGenerator(title='Stock Prices API') |
| 194 |
schema = generator.get_schema() |
| 195 |
|
| 196 |
The `request` argument is optional, and may be used if you want to apply |
| 197 |
per-user permissions to the resulting schema generation. |
| 198 |
|
| 199 |
This is a good point to override if you want to customize the generated |
| 200 |
dictionary For example you might wish to add terms of service to the [top-level |
| 201 |
`info` object][info-object]: |
| 202 |
|
| 203 |
``` |
| 204 |
class TOSSchemaGenerator(SchemaGenerator): |
| 205 |
def get_schema(self, *args, **kwargs): |
| 206 |
schema = super().get_schema(*args, **kwargs) |
| 207 |
schema["info"]["termsOfService"] = "https://example.com/tos.html" |
| 208 |
return schema |
| 209 |
``` |
| 210 |
|
| 211 |
## AutoSchema |
| 212 |
|
| 213 |
**Per-View Customization** |
| 214 |
|
| 215 |
```python |
| 216 |
from rest_framework.schemas.openapi import AutoSchema |
| 217 |
``` |
| 218 |
|
| 219 |
By default, view introspection is performed by an `AutoSchema` instance |
| 220 |
accessible via the `schema` attribute on `APIView`. |
| 221 |
|
| 222 |
auto_schema = some_view.schema |
| 223 |
|
| 224 |
`AutoSchema` provides the OpenAPI elements needed for each view, request method |
| 225 |
and path: |
| 226 |
|
| 227 |
* A list of [OpenAPI components][openapi-components]. In DRF terms these are |
| 228 |
mappings of serializers that describe request and response bodies. |
| 229 |
* The appropriate [OpenAPI operation object][openapi-operation] that describes |
| 230 |
the endpoint, including path and query parameters for pagination, filtering, |
| 231 |
and so on. |
| 232 |
|
| 233 |
```python |
| 234 |
components = auto_schema.get_components(...) |
| 235 |
operation = auto_schema.get_operation(...) |
| 236 |
``` |
| 237 |
|
| 238 |
In compiling the schema, `SchemaGenerator` calls `get_components()` and |
| 239 |
`get_operation()` for each view, allowed method, and path. |
| 240 |
|
| 241 |
!!! note |
| 242 |
The automatic introspection of components, and many operation |
| 243 |
parameters relies on the relevant attributes and methods of |
| 244 |
`GenericAPIView`: `get_serializer()`, `pagination_class`, `filter_backends`, |
| 245 |
etc. For basic `APIView` subclasses, default introspection is essentially limited to |
| 246 |
the URL kwarg path parameters for this reason. |
| 247 |
|
| 248 |
`AutoSchema` encapsulates the view introspection needed for schema generation. |
| 249 |
Because of this all the schema generation logic is kept in a single place, |
| 250 |
rather than being spread around the already extensive view, serializer and |
| 251 |
field APIs. |
| 252 |
|
| 253 |
Keeping with this pattern, try not to let schema logic leak into your own |
| 254 |
views, serializers, or fields when customizing the schema generation. You might |
| 255 |
be tempted to do something like this: |
| 256 |
|
| 257 |
```python |
| 258 |
class CustomSchema(AutoSchema): |
| 259 |
""" |
| 260 |
AutoSchema subclass using schema_extra_info on the view. |
| 261 |
""" |
| 262 |
|
| 263 |
... |
| 264 |
|
| 265 |
|
| 266 |
class CustomView(APIView): |
| 267 |
schema = CustomSchema() |
| 268 |
schema_extra_info = ... # some extra info |
| 269 |
``` |
| 270 |
|
| 271 |
Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the |
| 272 |
view. This is _OK_ (it doesn't actually hurt) but it means you'll end up with |
| 273 |
your schema logic spread out in a number of different places. |
| 274 |
|
| 275 |
Instead try to subclass `AutoSchema` such that the `extra_info` doesn't leak |
| 276 |
out into the view: |
| 277 |
|
| 278 |
```python |
| 279 |
class BaseSchema(AutoSchema): |
| 280 |
""" |
| 281 |
AutoSchema subclass that knows how to use extra_info. |
| 282 |
""" |
| 283 |
|
| 284 |
... |
| 285 |
|
| 286 |
|
| 287 |
class CustomSchema(BaseSchema): |
| 288 |
extra_info = ... # some extra info |
| 289 |
|
| 290 |
|
| 291 |
class CustomView(APIView): |
| 292 |
schema = CustomSchema() |
| 293 |
``` |
| 294 |
|
| 295 |
This style is slightly more verbose but maintains the encapsulation of the |
| 296 |
schema related code. It's more _cohesive_ in the _parlance_. It'll keep the |
| 297 |
rest of your API code more tidy. |
| 298 |
|
| 299 |
If an option applies to many view classes, rather than creating a specific |
| 300 |
subclass per-view, you may find it more convenient to allow specifying the |
| 301 |
option as an `__init__()` kwarg to your base `AutoSchema` subclass: |
| 302 |
|
| 303 |
```python |
| 304 |
class CustomSchema(BaseSchema): |
| 305 |
def __init__(self, **kwargs): |
| 306 |
# store extra_info for later |
| 307 |
self.extra_info = kwargs.pop("extra_info") |
| 308 |
super().__init__(**kwargs) |
| 309 |
|
| 310 |
|
| 311 |
class CustomView(APIView): |
| 312 |
schema = CustomSchema(extra_info=...) # some extra info |
| 313 |
``` |
| 314 |
|
| 315 |
This saves you having to create a custom subclass per-view for a commonly used option. |
| 316 |
|
| 317 |
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for |
| 318 |
the more commonly needed options do. |
| 319 |
|
| 320 |
### `AutoSchema` methods |
| 321 |
|
| 322 |
#### `get_components()` |
| 323 |
|
| 324 |
Generates the OpenAPI components that describe request and response bodies, |
| 325 |
deriving their properties from the serializer. |
| 326 |
|
| 327 |
Returns a dictionary mapping the component name to the generated |
| 328 |
representation. By default this has just a single pair but you may override |
| 329 |
`get_components()` to return multiple pairs if your view uses multiple |
| 330 |
serializers. |
| 331 |
|
| 332 |
#### `get_component_name()` |
| 333 |
|
| 334 |
Computes the component's name from the serializer. |
| 335 |
|
| 336 |
You may see warnings if your API has duplicate component names. If so you can override `get_component_name()` or pass the `component_name` `__init__()` kwarg (see below) to provide different names. |
| 337 |
|
| 338 |
#### `get_reference()` |
| 339 |
|
| 340 |
Returns a reference to the serializer component. This may be useful if you override `get_schema()`. |
| 341 |
|
| 342 |
|
| 343 |
#### `map_serializer()` |
| 344 |
|
| 345 |
Maps serializers to their OpenAPI representations. |
| 346 |
|
| 347 |
Most serializers should conform to the standard OpenAPI `object` type, but you may |
| 348 |
wish to override `map_serializer()` in order to customize this or other |
| 349 |
serializer-level fields. |
| 350 |
|
| 351 |
#### `map_field()` |
| 352 |
|
| 353 |
Maps individual serializer fields to their schema representation. The base implementation |
| 354 |
will handle the default fields that Django REST Framework provides. |
| 355 |
|
| 356 |
For `SerializerMethodField` instances, for which the schema is unknown, or custom field subclasses you should override `map_field()` to generate the correct schema: |
| 357 |
|
| 358 |
```python |
| 359 |
class CustomSchema(AutoSchema): |
| 360 |
"""Extension of ``AutoSchema`` to add support for custom field schemas.""" |
| 361 |
|
| 362 |
def map_field(self, field): |
| 363 |
# Handle SerializerMethodFields or custom fields here... |
| 364 |
# ... |
| 365 |
return super().map_field(field) |
| 366 |
``` |
| 367 |
|
| 368 |
Authors of third-party packages should aim to provide an `AutoSchema` subclass, |
| 369 |
and a mixin, overriding `map_field()` so that users can easily generate schemas |
| 370 |
for their custom fields. |
| 371 |
|
| 372 |
#### `get_tags()` |
| 373 |
|
| 374 |
OpenAPI groups operations by tags. By default tags taken from the first path |
| 375 |
segment of the routed URL. For example, a URL like `/users/{id}/` will generate |
| 376 |
the tag `users`. |
| 377 |
|
| 378 |
You can pass an `__init__()` kwarg to manually specify tags (see below), or |
| 379 |
override `get_tags()` to provide custom logic. |
| 380 |
|
| 381 |
#### `get_operation()` |
| 382 |
|
| 383 |
Returns the [OpenAPI operation object][openapi-operation] that describes the |
| 384 |
endpoint, including path and query parameters for pagination, filtering, and so |
| 385 |
on. |
| 386 |
|
| 387 |
Together with `get_components()`, this is the main entry point to the view |
| 388 |
introspection. |
| 389 |
|
| 390 |
#### `get_operation_id()` |
| 391 |
|
| 392 |
There must be a unique [operationid][openapi-operationid] for each operation. |
| 393 |
By default the `operationId` is deduced from the model name, serializer name or |
| 394 |
view name. The operationId looks like "listItems", "retrieveItem", |
| 395 |
"updateItem", etc. The `operationId` is camelCase by convention. |
| 396 |
|
| 397 |
#### `get_operation_id_base()` |
| 398 |
|
| 399 |
If you have several views with the same model name, you may see duplicate |
| 400 |
operationIds. |
| 401 |
|
| 402 |
In order to work around this, you can override `get_operation_id_base()` to |
| 403 |
provide a different base for name part of the ID. |
| 404 |
|
| 405 |
#### `get_serializer()` |
| 406 |
|
| 407 |
If the view has implemented `get_serializer()`, returns the result. |
| 408 |
|
| 409 |
#### `get_request_serializer()` |
| 410 |
|
| 411 |
By default returns `get_serializer()` but can be overridden to |
| 412 |
differentiate between request and response objects. |
| 413 |
|
| 414 |
#### `get_response_serializer()` |
| 415 |
|
| 416 |
By default returns `get_serializer()` but can be overridden to |
| 417 |
differentiate between request and response objects. |
| 418 |
|
| 419 |
### `AutoSchema.__init__()` kwargs |
| 420 |
|
| 421 |
`AutoSchema` provides a number of `__init__()` kwargs that can be used for |
| 422 |
common customizations, if the default generated values are not appropriate. |
| 423 |
|
| 424 |
The available kwargs are: |
| 425 |
|
| 426 |
* `tags`: Specify a list of tags. |
| 427 |
* `component_name`: Specify the component name. |
| 428 |
* `operation_id_base`: Specify the resource-name part of operation IDs. |
| 429 |
|
| 430 |
You pass the kwargs when declaring the `AutoSchema` instance on your view: |
| 431 |
|
| 432 |
``` |
| 433 |
class PetDetailView(generics.RetrieveUpdateDestroyAPIView): |
| 434 |
schema = AutoSchema( |
| 435 |
tags=['Pets'], |
| 436 |
component_name='Pet', |
| 437 |
operation_id_base='Pet', |
| 438 |
) |
| 439 |
... |
| 440 |
``` |
| 441 |
|
| 442 |
Assuming a `Pet` model and `PetSerializer` serializer, the kwargs in this |
| 443 |
example are probably not needed. Often, though, you'll need to pass the kwargs |
| 444 |
if you have multiple view targeting the same model, or have multiple views with |
| 445 |
identically named serializers. |
| 446 |
|
| 447 |
If your views have related customizations that are needed frequently, you can |
| 448 |
create a base `AutoSchema` subclass for your project that takes additional |
| 449 |
`__init__()` kwargs to save subclassing `AutoSchema` for each view. |
| 450 |
|
| 451 |
[cite]: https://www.heroku.com/blog/json_schema_for_heroku_platform_api/ |
| 452 |
[openapi]: https://github.com/OAI/OpenAPI-Specification |
| 453 |
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#specification-extensions |
| 454 |
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#operationObject |
| 455 |
[openapi-tags]: https://swagger.io/specification/#tagObject |
| 456 |
[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#fixed-fields-17 |
| 457 |
[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#componentsObject |
| 458 |
[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#referenceObject |
| 459 |
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator |
| 460 |
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen |
| 461 |
[info-object]: https://swagger.io/specification/#infoObject |
| 462 |
[drf-spectacular]: https://drf-spectacular.readthedocs.io/en/latest/readme.html |