一、簡介
- 生成API文檔平台
- 自動生成測試代碼
- 支持接口測試
二、安裝
- coreapi(必須)
- Pygments(可選)
- MarkDown(可選)
pip install -i https://pypi.douban.com/simple coreapi pip install -i https://pypi.douban.com/simple Pygments pip install -i https://pypi.douban.com/simple MarkDown
三、使用coreapi
1.最新版的DRF(>3.10)中,需要在全局配置文件settings.py中添加如下配置
REST_FRAMEWORK = { # 指定用於支持coreapi的Schema 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', }
2.在全局路由配置文件中添加以下代碼
from rest_framework.documentation import include_docs_urls from django.urls import path, include urlpatterns = [ path('docs/', include_docs_urls(title='測試平台接口文檔')), ]
3.添加注釋
1).單一方法的視圖
直接給視圖添加注釋即可
class ProjectsListView(ListAPIView): """ 返回所有項目信息 """
2).多個方法的視圖
class ProjectsListCreateView(ListCreateAPIView): """ get: 返回所有項目信息 post: 新建項目 """
3).視圖集
class ProjectsViewset(viewsets.ModelViewSet): """ create: 創建項目 retrieve: 獲取項目詳情數據 update: 完整更新項目 partial_update: 部分更新項目 destroy: 刪除項目 list: 獲取項目列表數據 names: 獲取所有項目名稱 interfaces: 獲取指定項目的所有接口數據 """
驗證結果:
四、使用drf-yasg
1.安裝
pip install drf-yasg
2.注冊drf_yasg
將'drf_yasg'添加到全局配置的INSTALLED_APPS中
INSTALLED_APPS = [ ... 'drf_yasg', ... ]
3.在全局路由文件urls.py文件中添加配置
# from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi from django.urls import path, re_path schema_view = get_schema_view( openapi.Info( title="API接口文檔平台", # 必傳 default_version='v1', # 必傳 description="這是一個美輪美奐的接口文檔", terms_of_service="http://api.xiaogongjin.site", contact=openapi.Contact(email="xiaogongjin@qq.com"), license=openapi.License(name="BSD License"), ), public=True, # permission_classes=(permissions.AllowAny,), # 權限類 ) urlpatterns = [ re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schemaredoc'), ]