安裝
- coreapi (必須)
- Pygments (可選)
- Markdown (可選)
使用coreapi
最新版的DRF(>3.10)中, 需要添加如下配置
REST_FRAMEWORK = {
# 指定用于支持coreapi的Schema
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
}
項目中添加URL
from rest_framework.documentation import include_docs_urls
from django.urls import path, include
urlpatterns = [
path('docs/', include_docs_urls(title='測試平臺接口文檔')),
]
-
演示:
image.png
image.png
-
添加注釋
單一方法的視圖
直接給視圖類添加注釋即可
class ProjectsListView(ListAPIView): """ 返回所有項目信息 """- 多個方法的視圖
class ProjectsListCreateView(ListCreateAPIView): """ get: 返回所有項目信息 post: 新建項目 """-
視圖集
class ProjectsViewset(viewsets.ModelViewSet): """ create: 創(chuàng)建項目 retrieve: 獲取項目詳情數(shù)據(jù) update: 完整更新項目 partial_update: 部分更新項目 destroy: 刪除項目 list: 獲取項目列表數(shù)據(jù) names: 獲取所有項目名稱 interfaces: 獲取指定項目的所有接口數(shù)據(jù) """
添加注釋后報告中就會顯示描述

image.png
但是drf3.12之后就不會支持,推薦使用另一種
使用drf-yasg
- 安裝
pip install drf-yasg
- 添加到INSTALLED_APPS中
INSTALLED_APPS = [
...
'drf_yasg',
...
]
- 在全局路由文件urls.py文件中添加配置
# 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="Lemon API接口文檔平臺", # 必傳
default_version='v1', # 必傳
description="這是一個美輪美奐的接口文檔",
terms_of_service="http://api.keyou.site",
contact=openapi.Contact(email="keyou100@qq.com"),
license=openapi.License(name="BSD License"),
),
public=True,
# permission_classes=(permissions.AllowAny,), # 權(quán)限類
)
urlpatterns = [
#三種不同風(fēng)格的接口文檔,自選其一
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='schema-redoc'),
]
驗證一
http://127.0.0.1:8000/swagger/

image.png

image.png
演示二
http://127.0.0.1:8000/swagger/

image.png
演示三

image.png
以上三種第一種適合平臺集成,第二種存在交互可以操作驗證,第三種更加詳細

