前言
任何一个系统,都不可缺少接口文档。django
也提供了十分方便的生成接口文档的工具类
一、coreapi
1、安装
pip install coreapi
pip install Pygments
pip install Markdown
2、使用
1、DRF
V3.10以上需要本步骤
setting.py
:
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}
2、添加接口文档路由,项目/urls.py
:
from django.contrib import admin
from django.urls import path, include, re_path
from rest_framework.documentation import clude_docs_urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('interfaces.urls')),
path('', include('projects.urls')),
path('docs/', include_docs_urls(title='平台接口文档',
description='接口文档平台'))
]
3、启动项目,访问127.0.0.1:8000/docs
:
3、文档添加注释
- 给单个视图类添加注释
- 在视图类添加注释即可
- 给视图类的多个方法添加注释
- 例子:
class ProjectsListCreateViewSet(ListCreateAPIView):
"""
get:
返回所有项目信息
post:
新建项目
"""
- 给视图集中的
action
添加注释 - 例子:
class ProjectsViewSet(viewsets.ModelViewSet):
"""
create:
创建项目
retrieve:
获取项目详情数据
update:
完整更新项目
partial_update:
部分更新项目
destroy:
删除项目
list:
获取项目列表数据
names:
获取所有项目名称
interfaces:
获取指定项目的所有接口数据
"""
二、drf-yasg
支持多种形式查看接口文档,包括swagger
1、安装
pip install drf-yasg
2、使用
1、注册app,setting.py
INSTALLED_APPS = [
# 第一个区域,django自己的app
# 第二个区域,第三方的app
'drf_yasg'
# 第三个区域,项目中自定义的app
]
2、添加接口文档路由,项目/urls.py
:
from django.contrib import admin
from django.urls import path, include, re_path
from rest_framework.documentation import clude_docs_urls
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title = 'API接口文档',
default_version='v1',
description='接口文档平台',
# terms_of_service='http://api.xxx.com',
contact=openapi.Contact(email='xxxx@qq.com'),
license=openapi.License(name='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'
),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0),
name='schema-redoc')
]
3、使用
1、访问json格式的swagger
127.0.0.1:8000/swagger.json
2、访问yaml格式的swagger
127.0.0.1:8000/swagger.yaml
3、访问正常格式的swagger
127.0.0.1:8000/swagger/
4、访问redoc
格式(开源项目一般是这种)
127.0.0.1:8000/redoc/
网友评论