使用 Django Rest Framework 3.5 自動生成 API 文檔
Auto-Generate Swagger Docs for your Django API

3.5新特性:
- Docstrings on your API's views are now included in your schema's definition.
- The helper method get_schema_view() has been added.
- The schema generation code has been fully documented and outlined here.
Django Rest Framework 3.5 附帶了get_schema_view方法,這個方法會為你的模式生成Django視圖,它還允許我們傳入一個Renderer(渲染器)類,渲染器將??告訴視圖應(yīng)該如何渲染。舉個例子:
from rest_framework.schemas import get_schema_view
from rest_framework.renderers import CoreJSONRenderer
schema_view = get_schema_view(
title='A Different API',
renderer_classes=[CoreJSONRenderer]
)
將會渲染你的api生成模式為JSON(具體來說,是遵循CoreAPI規(guī)范的JSON)
現(xiàn)在,使用django-rest-swagger中現(xiàn)成的渲染器,從我們的API生成swagger文檔非常的簡單。django-rest-swagger提供了兩個有用的渲染器:SwaggerUIRenderer 和 OpenAPIRenderer。我們兩個都用,因為SwaggerUIRenderer實際上使用渲染的OpenAPI格式。
讓我們嘗試下實現(xiàn)簡單的api接口和自動生成文檔:
bash/cmd 命令行操作
# 安裝包并構(gòu)建一個django項目,最后創(chuàng)建管理員
pip install Django
pip install djangorestframework
pip install django-rest-swagger
django-admin startproject api
cd api
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
api/settings.py 配置文件修改
# 在配置文件中修改兩項設(shè)置
INSTALLED_APPS = [
# [django core apps]
... # 保留之前的apps
'rest_framework',
'rest_framework_swagger',
]
...
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
api/urls.py 生成API
# 為了簡單,我們直接利用Django自身的基本用戶模型生成api接口
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
到此處,運行項目后 http://localhost:8000/api/users/ 的效果如下圖,登錄后可以 add, create 和 delete。下一步就是生成API的swagger文檔關(guān)鍵步了,它顯得非常簡潔。

api/urls.py 添加get_schema_view輔助函數(shù)
# existing imports
...
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
# existing serializer, viewset, router registrations code
...
# Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger
schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
# Inlcude the schema view in our urls.
urlpatterns = [
url(r'^docs/', schema_view, name="docs"),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
bash/cmd 運行項目
python manage.py runserver
在項目主目錄運行該命令,然后在瀏覽器打開
http://localhost:8000/docs/
嘗試點擊List Operations和Expand Operations,這用起來很酷。我們得到了數(shù)據(jù)模型api的操作列表,使用樣例,甚至可以直接在界面中填充表單來使用這些api。

此外,Django Rest Framework 3.5 使得我們在操作旁邊添加提示變得極為容易,只需要在類的文檔字符串中對應(yīng)合適的方法名稱添加你想要的文字就行了。
# imports and UserSerializer
...
class UserViewSet(viewsets.ModelViewSet):
"""
retrieve:
Return a user instance.
list:
Return all users, ordered by most recently joined.
create:
Create a new user.
delete:
Remove an existing user.
partial_update:
Update one or more fields on an existing user.
update:
Update a user.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
# routing
...

最終的api/urls.py
# 為了簡單,我們直接利用Django自身的基本用戶模型生成api接口
# just inline a simple api endpoint at 'users/' that exposes Django's base User model
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
from django.contrib import admin
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
"""
retrieve:
Return a user instance.
list:
Return all users, ordered by most recently joined.
create:
Create a new user.
delete:
Remove an existing user.
partial_update:
Update one or more fields on an existing user.
update:
Update a user.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger
schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^docs/', schema_view, name="docs"),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^admin/', admin.site.urls),
]
