* Add DRF OpenAPI as a 3rd party tool for DRF doc * Add image * Add third party packages section to schema doc * Add DRF OpenAPI reference
9.6 KiB
Documenting your API
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.
— Roy Fielding, REST APIs must be hypertext driven
REST framework provides built-in support for API documentation. There are also a number of great third-party documentation tools available.
Built-in API documentation
The built-in API documentation includes:
- Documentation of API endpoints.
- Automatically generated code samples for each of the available API client libraries.
- Support for API interaction.
Installation
The coreapi
library is required as a dependancy for the API docs. Make sure
to install the latest version. The pygments
and markdown
libraries
are optional but recommended.
To install the API documentation, you'll need to include it in your projects URLconf:
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
url(r'^docs/', include_docs_urls(title='My API title'))
]
This will include two different views:
/docs/
- The documentation page itself./docs/schema.js
- A JavaScript resource that exposes the API schema.
Documenting your views
You can document your views by including docstrings that describe each of the available actions. For example:
class UserList(generics.ListAPIView):
"""
Return a list of all the existing users.
"""
If a view supports multiple methods, you should split your documentation using method:
style delimiters.
class UserList(generics.ListCreateAPIView):
"""
get:
Return a list of all the existing users.
post:
Create a new user instance.
"""
When using viewsets, you should use the relevant action names as delimiters.
class UserViewSet(viewsets.ModelViewSet):
"""
retrieve:
Return the given user.
list:
Return a list of all the existing users.
create:
Create a new user instance.
"""
Third party packages
There are a number of mature third-party packages for providing API documentation.
DRF OpenAPI
DRF OpenAPI bridges the gap between OpenAPI specification and tool chain with the schema exposed out-of-the-box by Django Rest Framework. Its goals are:
- To be dropped into any existing DRF project without any code change necessary.
- Provide clear disctinction between request schema and response schema.
- Provide a versioning mechanism for each schema. Support defining schema by version range syntax, e.g. >1.0, <=2.0
- Support multiple response codes, not just 200
- All this information should be bound to view methods, not view classes.
It also tries to stay current with the maturing schema generation mechanism provided by DRF.
DRF Docs
DRF Docs allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the website while there is also a demo available for people to see what it looks like. Live API Endpoints allow you to utilize the endpoints from within the documentation in a neat way.
Features include customizing the template with your branding, settings for hiding the docs depending on the environment and more.
Both this package and Django REST Swagger are fully documented, well supported, and come highly recommended.
Django REST Swagger
Marc Gibbons' Django REST Swagger integrates REST framework with the Swagger API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints.
Django REST Swagger supports REST framework versions 2.3 and above.
Mark is also the author of the REST Framework Docs package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger.
Both this package and DRF docs are fully documented, well supported, and come highly recommended.
DRF AutoDocs
Oleksander Mashianovs' DRF Auto Docs automated api renderer.
Collects almost all the code you written into documentation effortlessly.
Supports:
- functional view docs
- tree-like structure
- Docstrings:
- markdown
- preserve space & newlines
- formatting with nice syntax
- Fields:
- choices rendering
- help_text (to specify SerializerMethodField output, etc)
- smart read_only/required rendering
- Endpoint properties:
- filter_backends
- authentication_classes
- permission_classes
- extra url params(GET params)
Apiary
There are various other online tools and services for providing API documentation. One notable service is Apiary. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools.
Self describing APIs
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.
Setting the title
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.
For example, the view UserListView
, will be named User List
when presented in the browsable API.
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
.
Setting the description
The description in the browsable API is generated from the docstring of the view or viewset.
If the python markdown
library is installed, then markdown syntax may be used in the docstring, and will be converted to HTML in the browsable API. For example:
class AccountListView(views.APIView):
"""
Returns a list of all **active** accounts in the system.
For more details on how accounts are activated please [see here][ref].
[ref]: http://example.com/activating-accounts
"""
Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the the list and retrieve views, use docstring sections as described in Schemas as documentation: Examples.
The OPTIONS
method
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.
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.
You can modify the response behavior to OPTIONS
requests by overriding the metadata
view method. For example:
def metadata(self, request):
"""
Don't include the view description in OPTIONS responses.
"""
data = super(ExampleView, self).metadata(request)
data.pop('description')
return data
The hypermedia approach
To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends.
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.
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 section of the documentation includes pointers to background reading, as well as links to various hypermedia formats.