Django Rest Framework 3.5 自动生成 API 文档

96
treelake
0.3 2016.11.08 09:31* 字数 495

使用 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(渲染器)类,渲染器将​​告诉视图应该如何渲染。举个例子:

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规范的JSON)
现在,使用django-rest-swagger中现成的渲染器,从我们的API生成swagger文档非常的简单。django-rest-swagger提供了两个有用的渲染器:SwaggerUIRenderer 和 OpenAPIRenderer。我们两个都用,因为SwaggerUIRenderer实际上使用渲染的OpenAPI格式。
让我们尝试下实现简单的api接口和自动生成文档


bash/cmd 命令行操作
# 安装包并构建一个django项目,最后创建管理员
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 配置文件修改
# 在配置文件中修改两项设置
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文档关键步了,它显得非常简洁

api/urls.py 添加get_schema_view辅助函数
# 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,这用起来很酷。我们得到了数据模型api的操作列表,使用样例,甚至可以直接在界面中填充表单来使用这些api。

此外,Django Rest Framework 3.5 使得我们在操作旁边添加提示变得极为容易,只需要在类的文档字符串中对应合适的方法名称添加你想要的文字就行了。

# 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),
]
Python