Django Rest Framework 3.8 自动生成 API 文档

使用 Django Rest Framework 3.8 自动生成 API 文档

原文地址:https://www.jianshu.com/p/dc77f652e7d7

pip install djangorestframework
pip install markdown
pip install django-filter
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),
]










没有更多推荐了,返回首页