關於swagger
https://www.jianshu.com/p/349e130e40d5
Swagger能成為最受歡迎的REST APIs文檔生成工具之一,有以下幾個原因:
- Swagger 可以生成一個具有互動性的API控制台,開發者可以用來快速學習和嘗試API。
- Swagger 可以生成客戶端SDK代碼用於各種不同的平台上的實現。
- Swagger 文件可以在許多不同的平台上從代碼注釋中自動生成。
- Swagger 有一個強大的社區,里面有許多強悍的貢獻者。
使用版本
Django==3.1.2
djangorestframework==3.12.2
drf-yasg==1.20.0
此處我的django版本是3.+,而django-swagger不支持3.+版本,所以引用drf-yasg模塊,django3.0以下的版本可以直接用django-swagger,這里具體介紹drf-yasg的基本用法
修改settings.py
INSTALLED_APPS = [ ...... 'drf_yasg', 'rest_framework', ...... ]
添加url.py
項目根目錄的url文件最上面,添加文檔描述
from drf_yasg.views import get_schema_view from drf_yasg import openapi # swager文檔 schema_view = get_schema_view( openapi.Info( title="測試項目API", default_version='v1.0', description="測試工程接口文檔", terms_of_service="https://www.baidu.com", contact=openapi.Contact(email="baidu@163.com"), license=openapi.License(name="BSD License"), ), public=True, )
添加路由,用於訪問swagger
urlpatterns = [
... # swager url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ]
api文檔編寫view.py
當然不可能配置了路由以后所有的文檔就給你自動生成了,具體的接口配置還需要你自己到實行的view界面進行配置,這里先介紹最簡單的配置方法,
from drf_yasg.utils import swagger_auto_schema from rest_framework.views import APIView class QueryTesterCases(APIView): def post(self, request): groupId = request.POST.get('groupId') beginTime = request.POST.get('beginTime') endTime = request.POST.get('endTime') return JsonResponse(TapdCasesManage().queryTesterCases(beginTime=beginTime, endTime=endTime, groupId=groupId))
此時一個最簡單的接口文檔便寫好了,可以先打開swagger地址查看接口文檔。
啟動服務進入:http://127.0.0.1:8000/swagger/
由於我們沒有對接口進行任何描述,所以點開接口以后並沒有任何接口信息