> 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.
## Install Core API & PyYAML
You'll need to install the `coreapi` package in order to add schema support
for REST framework. You probably also want to install `pyyaml`, so that you
can render the schema into the commonly used YAML-based OpenAPI format.
pip install coreapi pyyaml
## Quickstart
There are two different ways you can serve a schema description for your API.
### Generating a schema with the `generateschema` management command
To generate a static API schema, use the `generateschema` management command.
```shell
$ python manage.py generateschema > schema.yml
```
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.
### Adding a view with `get_schema_view`
To add a dynamically generated schema view to your API, use `get_schema_view`.
```python
from rest_framework.schemas import get_schema_view
The `request` argument is optional, and may be used if you want to apply per-user
permissions to the resulting schema generation.
### get_links(self, request)
Return a nested dictionary containing all the links that should be included in the API schema.
This is a good point to override if you want to modify the resulting structure of the generated schema,
as you can build a new dictionary with a different layout.
## AutoSchema
A class that deals with introspection of individual views for schema generation.
`AutoSchema` is attached to `APIView` via the `schema` attribute.
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
the generated fields. Generated fields with a matching `name` will be overwritten.
class CustomView(APIView):
schema = AutoSchema(manual_fields=[
coreapi.Field(
"my_extra_field",
required=True,
location="path",
schema=coreschema.String()
),
])
For more advanced customisation subclass `AutoSchema` to customise schema generation.
class CustomViewSchema(AutoSchema):
"""
Overrides `get_link()` to provide Custom Behavior X
"""
def get_link(self, path, method, base_url):
link = super().get_link(path, method, base_url)
# Do something to customize link here...
return link
class MyView(APIView):
schema = CustomViewSchema()
The following methods are available to override.
### get_link(self, path, method, base_url)
Returns a `coreapi.Link` instance corresponding to the given view.
This is the main entry point.
You can override this if you need to provide custom behaviors for particular views.
### get_description(self, path, method)
Returns a string to use as the link description. By default this is based on the
view docstring as described in the "Schemas as Documentation" section above.
### get_encoding(self, path, method)
Returns a string to indicate the encoding for any request body, when interacting
with the given view. Eg. `'application/json'`. May return a blank string for views
that do not expect a request body.
### get_path_fields(self, path, method):
Return a list of `coreapi.Field()` instances. One for each path parameter in the URL.
### get_serializer_fields(self, path, method)
Return a list of `coreapi.Field()` instances. One for each field in the serializer class used by the view.
### get_pagination_fields(self, path, method)
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
### get_filter_fields(self, path, method)
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
### get_manual_fields(self, path, method)
Return a list of `coreapi.Field()` instances to be added to or replace generated fields. Defaults to (optional) `manual_fields` passed to `AutoSchema` constructor.
May be overridden to customise manual fields by `path` or `method`. For example, a per-method adjustment may look like this:
```python
def get_manual_fields(self, path, method):
"""Example adding per-method fields."""
extra_fields = []
if method=='GET':
extra_fields = # ... list of extra fields for GET ...
if method=='POST':
extra_fields = # ... list of extra fields for POST ...
Utility `staticmethod`. Encapsulates logic to add or replace fields from a list
by `Field.name`. May be overridden to adjust replacement criteria.
## ManualSchema
Allows manually providing a list of `coreapi.Field` instances for the schema,
plus an optional description.
class MyView(APIView):
schema = ManualSchema(fields=[
coreapi.Field(
"first_field",
required=True,
location="path",
schema=coreschema.String()
),
coreapi.Field(
"second_field",
required=True,
location="path",
schema=coreschema.String()
),
]
)
The `ManualSchema` constructor takes two arguments:
**`fields`**: A list of `coreapi.Field` instances. Required.
**`description`**: A string description. Optional.
**`encoding`**: Default `None`. A string encoding, e.g `application/json`. Optional.
---
## Core API
This documentation gives a brief overview of the components within the `coreapi`
package that are used to represent an API schema.
Note that these classes are imported from the `coreapi` package, rather than
from the `rest_framework` package.
### Document
Represents a container for the API schema.
#### `title`
A name for the API.
#### `url`
A canonical URL for the API.
#### `content`
A dictionary, containing the `Link` objects that the schema contains.
In order to provide more structure to the schema, the `content` dictionary
may be nested, typically to a second level. For example:
content={
"bookings": {
"list": Link(...),
"create": Link(...),
...
},
"venues": {
"list": Link(...),
...
},
...
}
### Link
Represents an individual API endpoint.
#### `url`
The URL of the endpoint. May be a URI template, such as `/users/{username}/`.
#### `action`
The HTTP method associated with the endpoint. Note that URLs that support
more than one HTTP method, should correspond to a single `Link` for each.
#### `fields`
A list of `Field` instances, describing the available parameters on the input.
#### `description`
A short description of the meaning and intended usage of the endpoint.
### Field
Represents a single input parameter on a given API endpoint.
#### `name`
A descriptive name for the input.
#### `required`
A boolean, indicated if the client is required to included a value, or if
the parameter can be omitted.
#### `location`
Determines how the information is encoded into the request. Should be one of
the following strings:
**"path"**
Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
These fields will normally correspond with [named arguments in the project URL conf][named-arguments].
**"query"**
Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests.
These fields will normally correspond with pagination and filtering controls on a view.
**"form"**
Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link.
These fields will normally correspond with serializer fields on a view.
**"body"**
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields.
These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views.
#### `encoding`
**"application/json"**
JSON encoded request content. Corresponds to views using `JSONParser`.
Valid only if either one or more `location="form"` fields, or a single
`location="body"` field is included on the `Link`.
**"multipart/form-data"**
Multipart encoded request content. Corresponds to views using `MultiPartParser`.
Valid only if one or more `location="form"` fields is included on the `Link`.
**"application/x-www-form-urlencoded"**
URL encoded request content. Corresponds to views using `FormParser`. Valid
only if one or more `location="form"` fields is included on the `Link`.
**"application/octet-stream"**
Binary upload request content. Corresponds to views using `FileUploadParser`.
Valid only if a `location="body"` field is included on the `Link`.
#### `description`
A short description of the meaning and intended usage of the input field.