https://blog.csdn.net/qq_32502511/article/details/80346968

Django Rest Framework 3.8 自动生成 API 文档

2018年05月17日 10:26:43 Liu-YanLin 阅读数:3938更多

个人分类: django

所属专栏: python

使用 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

  1. python manage.py makemigrations

  2. python manage.py migrate

  3. python manage.py createsuperuser

api/settings.py 配置文件修改
  1. # 在配置文件中修改两项设置

  2. INSTALLED_APPS = [

  3. # [django core apps]

  4. … # 保留之前的apps

  5. ‘rest_framework’,

  6. ‘rest_framework_swagger’,

  7. ]

  8. REST_FRAMEWORK = {

  9. # Use Django’s standard `django.contrib.auth` permissions,

  10. # or allow read-only access for unauthenticated users.

  11. ‘DEFAULT_PERMISSION_CLASSES’: [

  12. ‘rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly’

  13. ]

  14. }

api/urls.py 生成API
  1. # 为了简单,我们直接利用Django自身的基本用户模型生成api接口

  2. from django.conf.urls import url, include

  3. from django.contrib.auth.models import User

  4. from rest_framework import routers, serializers, viewsets

  1. # Serializers define the API representation.

  2. class UserSerializer(serializers.HyperlinkedModelSerializer):

  3. class Meta:

  4. model = User

  5. fields = ('url', 'username', 'email', 'is_staff')

  1. # ViewSets define the view behavior.

  2. class UserViewSet(viewsets.ModelViewSet):

  3. queryset = User.objects.all()

  4. serializer_class = UserSerializer

  1. # Routers provide an easy way of automatically determining the URL conf.

  2. router = routers.DefaultRouter()

  3. router.register(r'users', UserViewSet)

  1. # Wire up our API using automatic URL routing.

  2. # Additionally, we include login URLs for the browsable API.

  3. urlpatterns = [

  4. url(r'^api/', include(router.urls)),

  5. url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))

  6. ]

到此处,运行项目后 http://localhost:8000/api/users/ 的效果如下图,登录后可以 add, create 和 delete。下一步就是生成API的swagger文档关键步了,它显得非常简洁。

api/urls.py 添加get_schema_view辅助函数
  1. # existing imports

  2. ...

  3. from rest_framework.schemas import get_schema_view

  4. from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer

  1. # existing serializer, viewset, router registrations code

  2. ...

  1. # Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger

  2. schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])

  1. # Inlcude the schema view in our urls.

  2. urlpatterns = [

  3. url(r'^docs/', schema_view, name="docs"),

  4. url(r'^api/', include(router.urls)),

  5. url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))

  6. ]

bash/cmd 运行项目
python manage.py runserver

在项目主目录运行该命令,然后在浏览器打开 http://localhost:8000/docs/ 尝试点击List Operations和Expand Operations,这用起来很酷。我们得到了数据模型api的操作列表,使用样例,甚至可以直接在界面中填充表单来使用这些api。

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

  1. # imports and UserSerializer

  2. ...

  3. class UserViewSet(viewsets.ModelViewSet):

  4. """

  5. retrieve:

  6. Return a user instance.

  1. list:

  2. Return all users, ordered by most recently joined.

  1. create:

  2. Create a new user.

  1. delete:

  2. Remove an existing user.

  1. partial_update:

  2. Update one or more fields on an existing user.

  1. update:

  2. Update a user.

  3. """

  4. queryset = User.objects.all()

  5. serializer_class = UserSerializer

  1. # routing

  2. ...

最终的api/urls.py
  1. # 为了简单,我们直接利用Django自身的基本用户模型生成api接口

  2. # just inline a simple api endpoint at 'users/' that exposes Django's base User model

  3. from django.conf.urls import url, include

  4. from django.contrib.auth.models import User

  5. from rest_framework import routers, serializers, viewsets

  6. from rest_framework.schemas import get_schema_view

  7. from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer

  1. from django.contrib import admin
  1. # Serializers define the API representation.

  2. class UserSerializer(serializers.HyperlinkedModelSerializer):

  3. class Meta:

  4. model = User

  5. fields = ('url', 'username', 'email', 'is_staff')

  1. # ViewSets define the view behavior.

  2. class UserViewSet(viewsets.ModelViewSet):

  3. """

  4. retrieve:

  5. Return a user instance.

  1. list:

  2. Return all users, ordered by most recently joined.

  1. create:

  2. Create a new user.

  1. delete:

  2. Remove an existing user.

  1. partial_update:

  2. Update one or more fields on an existing user.

  1. update:

  2. Update a user.

  3. """

  1. queryset = User.objects.all()

  2. serializer_class = UserSerializer

  1. # Routers provide an easy way of automatically determining the URL conf.

  2. router = routers.DefaultRouter()

  3. router.register(r'users', UserViewSet)

  1. # Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger

  2. schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])

  1. # Wire up our API using automatic URL routing.

  2. # Additionally, we include login URLs for the browsable API.

  3. urlpatterns = [

  4. url(r'^docs/', schema_view, name="docs"),

  5. url(r'^api/', include(router.urls)),

  6. url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

  7. url(r'^admin/', admin.site.urls),

  8. ]