2019-07-01 05:04:36 +03:00
---
source:
2019-09-27 19:47:51 +03:00
- schemas
2019-07-01 05:04:36 +03:00
---
2016-07-04 18:38:17 +03:00
2019-07-08 15:09:05 +03:00
# Schema
2016-07-04 18:38:17 +03:00
> 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.
>
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
API schemas are a useful tool that allow for a range of use cases, including
generating reference documentation, or driving dynamic client libraries that
can interact with your API.
2019-07-08 15:09:05 +03:00
Django REST Framework provides support for automatic generation of
[OpenAPI][openapi] schemas.
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
## Generating an OpenAPI Schema
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
### Install `pyyaml`
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
You'll need to install `pyyaml` , so that you can render your generated schema
into the commonly used YAML-based OpenAPI format.
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
pip install pyyaml
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
### Generating a static schema with the `generateschema` management command
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
If your schema is static, you can use the `generateschema` management command:
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
```bash
2020-02-12 22:35:54 +03:00
./manage.py generateschema --file openapi-schema.yml
2018-10-04 16:05:55 +03:00
```
Once you've generated a schema in this way you can annotate it with any
additional information that cannot be automatically inferred by the schema
generator.
You might want to check your API schema into version control and update it
with each new release, or serve the API schema from your site's static media.
2019-07-08 15:09:05 +03:00
### Generating a dynamic schema with `SchemaView`
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
If you require a dynamic schema, because foreign key choices depend on database
values, for example, you can route a `SchemaView` that will generate and serve
your schema on demand.
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
To route a `SchemaView` , use the `get_schema_view()` helper.
In `urls.py` :
2018-10-04 16:05:55 +03:00
2019-07-08 15:09:05 +03:00
```python
2019-07-16 23:32:19 +03:00
from rest_framework.schemas import get_schema_view
2018-10-04 16:05:55 +03:00
urlpatterns = [
2019-07-08 15:09:05 +03:00
# ...
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator` .
# * Provide view name for use with `reverse()` .
path('openapi', get_schema_view(
title="Your Project",
2019-09-03 17:07:30 +03:00
description="API for all things …",
version="1.0.0"
2019-07-08 15:09:05 +03:00
), name='openapi-schema'),
# ...
2018-10-04 16:05:55 +03:00
]
```
2019-07-08 15:09:05 +03:00
#### `get_schema_view()`
2016-07-04 18:38:17 +03:00
2019-07-08 15:09:05 +03:00
The `get_schema_view()` helper takes the following keyword arguments:
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
* `title` : May be used to provide a descriptive title for the schema definition.
* `description` : Longer descriptive text.
2019-11-06 23:54:12 +03:00
* `version` : The version of the API.
2019-07-08 15:09:05 +03:00
* `url` : May be used to pass a canonical base URL for the schema.
2016-07-04 18:38:17 +03:00
2019-07-08 15:09:05 +03:00
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/'
)
2016-07-04 18:38:17 +03:00
2019-07-08 15:09:05 +03:00
* `urlconf` : A string representing the import path to the URL conf that you want
to generate an API schema for. This defaults to the value of Django's
`ROOT_URLCONF` setting.
2016-07-04 18:38:17 +03:00
2019-07-08 15:09:05 +03:00
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
urlconf='myproject.urls'
)
2019-10-22 21:10:15 +03:00
2019-07-08 15:09:05 +03:00
* `patterns` : List of url patterns to limit the schema introspection to. If you
only want the `myproject.api` urls to be exposed in the schema:
2016-07-04 18:38:17 +03:00
2019-07-08 15:09:05 +03:00
schema_url_patterns = [
url(r'^api/', include('myproject.api.urls')),
]
schema_view = get_schema_view(
title='Server Monitoring API',
url='https://www.example.org/api/',
patterns=schema_url_patterns,
)
* `generator_class` : May be used to specify a `SchemaGenerator` subclass to be
passed to the `SchemaView` .
* `authentication_classes` : May be used to specify the list of authentication
classes that will apply to the schema endpoint. Defaults to
`settings.DEFAULT_AUTHENTICATION_CLASSES`
* `permission_classes` : May be used to specify the list of permission classes
that will apply to the schema endpoint. Defaults to
`settings.DEFAULT_PERMISSION_CLASSES` .
* `renderer_classes` : May be used to pass the set of renderer classes that can
be used to render the API root endpoint.
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
## Customizing Schema Generation
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
You may customize schema generation at the level of the schema as a whole, or
on a per-view basis.
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
### Schema Level Customization
In order to customize the top-level schema sublass
`rest_framework.schemas.openapi.SchemaGenerator` and provide it as an argument
to the `generateschema` command or `get_schema_view()` helper function.
#### SchemaGenerator
A class that walks a list of routed URL patterns, requests the schema for each
view and collates the resulting OpenAPI schema.
Typically you'll instantiate `SchemaGenerator` with a `title` argument, like so:
generator = SchemaGenerator(title='Stock Prices API')
Arguments:
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
* `title` **required** : The name of the API.
* `description` : Longer descriptive text.
2019-09-03 17:07:30 +03:00
* `version` : The version of the API. Defaults to `0.1.0` .
2019-07-08 15:09:05 +03:00
* `url` : The root URL of the API schema. This option is not required unless the schema is included under path prefix.
* `patterns` : A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
* `urlconf` : A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF` .
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
##### get_schema(self, request)
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
Returns a dictionary that represents the OpenAPI schema:
generator = SchemaGenerator(title='Stock Prices API')
2017-09-14 11:46:34 +03:00
schema = generator.get_schema()
2019-07-08 15:09:05 +03:00
The `request` argument is optional, and may be used if you want to apply
per-user permissions to the resulting schema generation.
2019-10-24 09:54:37 +03:00
This is a good point to override if you want to customize the generated
2019-07-08 15:09:05 +03:00
dictionary, for example to add custom
[specification extensions][openapi-specification-extensions].
### Per-View Customization
2017-09-14 11:46:34 +03:00
By default, view introspection is performed by an `AutoSchema` instance
accessible via the `schema` attribute on `APIView` . This provides the
2019-07-08 15:09:05 +03:00
appropriate [Open API operation object][openapi-operation] for the view,
request method and path:
2017-09-14 11:46:34 +03:00
auto_schema = view.schema
2019-07-08 15:09:05 +03:00
operation = auto_schema.get_operation(...)
2017-09-14 11:46:34 +03:00
2019-07-08 15:09:05 +03:00
In compiling the schema, `SchemaGenerator` calls `view.schema.get_operation()`
for each view, allowed method, and path.
2017-09-14 11:46:34 +03:00
2017-12-04 12:52:59 +03:00
---
**Note**: For basic `APIView` subclasses, default introspection is essentially
limited to the URL kwarg path parameters. For `GenericAPIView`
subclasses, which includes all the provided class based views, `AutoSchema` will
2019-10-24 21:31:12 +03:00
attempt to introspect serializer, pagination and filter fields, as well as
2017-12-04 12:52:59 +03:00
provide richer path field descriptions. (The key hooks here are the relevant
`GenericAPIView` attributes and methods: `get_serializer` , `pagination_class` ,
`filter_backends` and so on.)
---
2019-10-24 09:54:37 +03:00
In order to customize the operation generation, you should provide an `AutoSchema` subclass, overriding `get_operation()` as you need:
2017-09-14 11:46:34 +03:00
from rest_framework.views import APIView
2019-07-08 15:09:05 +03:00
from rest_framework.schemas.openapi import AutoSchema
2017-09-14 11:46:34 +03:00
class CustomSchema(AutoSchema):
2019-10-24 09:54:37 +03:00
def get_operation(...):
2017-10-06 14:18:31 +03:00
# Implement custom introspection here (or in other sub-methods)
2017-09-14 11:46:34 +03:00
class CustomView(APIView):
2019-07-08 15:09:05 +03:00
"""APIView subclass with custom schema introspection."""
2017-09-14 11:46:34 +03:00
schema = CustomSchema()
2019-07-08 15:09:05 +03:00
This provides complete control over view introspection.
2017-09-14 11:46:34 +03:00
2017-09-20 12:29:47 +03:00
You may disable schema generation for a view by setting `schema` to `None` :
2017-09-14 11:46:34 +03:00
class CustomView(APIView):
2016-07-04 18:38:17 +03:00
...
2019-07-08 15:09:05 +03:00
schema = None # Will not appear in schema
2016-07-04 18:38:17 +03:00
2019-07-08 15:09:05 +03:00
This also applies to extra actions for `ViewSet` s:
2017-10-02 12:16:33 +03:00
2019-07-08 15:09:05 +03:00
class CustomViewSet(viewsets.ModelViewSet):
2017-10-02 12:16:33 +03:00
2019-07-08 15:09:05 +03:00
@action (detail=True, schema=None)
def extra_action(self, request, pk=None):
...
2018-01-02 16:51:54 +03:00
2019-07-08 15:09:05 +03:00
If you wish to provide a base `AutoSchema` subclass to be used throughout your
project you may adjust `settings.DEFAULT_SCHEMA_CLASS` appropriately.
2018-01-02 16:51:54 +03:00
2019-07-08 15:09:05 +03:00
[openapi]: https://github.com/OAI/OpenAPI-Specification
[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions
2019-10-24 09:54:37 +03:00
[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject