[Django] 06 - API Doc: Swagger
Ref: https://testdriven.io/courses/tdd-django/api-documentation/
一、安装
文件:requirements.txt
drf-yasg==1.17.1
文件:settings.py 集成 “装备”。
# app/drf_project/urls.py from django.contrib import admin from django.urls import include, path
from .views import ping
from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title = "Movies API", default_version = "v1", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path("admin/", admin.site.urls), path("ping/", ping, name="ping"), path("swagger-docs/", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"), # <--- path("", include("movies.urls")), ]
二、测试
有部分功能重复。
Goto: http://localhost:8000/swagger-docs/
但右边的 "No parameters" 是怎么回事?
-
Custom Schema
使输入input可用。解决 "No parameters" 的问题。
@swagger_auto_schema( request_body=openapi.Schema( type = openapi.TYPE_OBJECT, properties = { "title": openapi.Schema(type=openapi.TYPE_STRING), "genre": openapi.Schema(type=openapi.TYPE_STRING), "year": openapi.Schema(type=openapi.TYPE_STRING), }, ) ) def post(self, request, format=None): serializer = MovieSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ "title": openapi.Schema(type=openapi.TYPE_STRING), "genre": openapi.Schema(type=openapi.TYPE_STRING), "year": openapi.Schema(type=openapi.TYPE_STRING), }, ) ) def put(self, request, pk, format=None): movie = self.get_object(pk) serializer = MovieSerializer(movie, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
三、文档
自动生成在线文档。
Goto: http://localhost:8000/docs/
先预加载数据,再测试。
jeffrey@unsw-ThinkPad-T490:app$ ls db.sqlite3 Dockerfile drf_project entrypoint.sh manage.py movies movies.json pytest.ini requirements.txt tests jeffrey@unsw-ThinkPad-T490:app$ docker-compose exec movies python manage.py loaddata movies.json Installed 3 object(s) from 1 fixture(s)
End.