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

 

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

 

  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
  5. # Serializers define the API representation.
  6. class UserSerializer(serializers.HyperlinkedModelSerializer):
  7. class Meta:
  8. model = User
  9. fields = ('url', 'username', 'email', 'is_staff')
  10. # ViewSets define the view behavior.
  11. class UserViewSet(viewsets.ModelViewSet):
  12. queryset = User.objects.all()
  13. serializer_class = UserSerializer
  14. # Routers provide an easy way of automatically determining the URL conf.
  15. router = routers.DefaultRouter()
  16. router.register(r'users', UserViewSet)
  17. # Wire up our API using automatic URL routing.
  18. # Additionally, we include login URLs for the browsable API.
  19. urlpatterns = [
  20. url(r'^api/', include(router.urls)),
  21. url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
  22. ]

 

到此处,运行项目后 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
  5. # existing serializer, viewset, router registrations code
  6. ...
  7. # Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger
  8. schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
  9. # Inlcude the schema view in our urls.
  10. urlpatterns = [
  11. url(r'^docs/', schema_view, name="docs"),
  12. url(r'^api/', include(router.urls)),
  13. url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
  14. ]

 

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.
  7. list:
  8. Return all users, ordered by most recently joined.
  9. create:
  10. Create a new user.
  11. delete:
  12. Remove an existing user.
  13. partial_update:
  14. Update one or more fields on an existing user.
  15. update:
  16. Update a user.
  17. """
  18. queryset = User.objects.all()
  19. serializer_class = UserSerializer
  20. # routing
  21. ...

 

最终的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
  8. from django.contrib import admin
  9. # Serializers define the API representation.
  10. class UserSerializer(serializers.HyperlinkedModelSerializer):
  11. class Meta:
  12. model = User
  13. fields = ('url', 'username', 'email', 'is_staff')
  14. # ViewSets define the view behavior.
  15. class UserViewSet(viewsets.ModelViewSet):
  16. """
  17. retrieve:
  18. Return a user instance.
  19. list:
  20. Return all users, ordered by most recently joined.
  21. create:
  22. Create a new user.
  23. delete:
  24. Remove an existing user.
  25. partial_update:
  26. Update one or more fields on an existing user.
  27. update:
  28. Update a user.
  29. """
  30. queryset = User.objects.all()
  31. serializer_class = UserSerializer
  32. # Routers provide an easy way of automatically determining the URL conf.
  33. router = routers.DefaultRouter()
  34. router.register(r'users', UserViewSet)
  35. # Create our schema's view w/ the get_schema_view() helper method. Pass in the proper Renderers for swagger
  36. schema_view = get_schema_view(title='Users API', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
  37. # Wire up our API using automatic URL routing.
  38. # Additionally, we include login URLs for the browsable API.
  39. urlpatterns = [
  40. url(r'^docs/', schema_view, name="docs"),
  41. url(r'^api/', include(router.urls)),
  42. url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
  43. url(r'^admin/', admin.site.urls),
  44. ]

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注