##serializers.py class CategorySerializer(serializers.ModelSerializer): """ Serializing Categories """ class Meta: model = Category fields = [ 'id', 'name', 'slug' ] read_only_fields = [ 'slug', ] ##views.py username_param = openapi.Parameter('username', in_=openapi.IN_QUERY, description='Username', type=openapi.TYPE_STRING) email = openapi.Parameter('email', in_=openapi.IN_QUERY, description='Email', type=openapi.TYPE_STRING) category_response = openapi.Response('response description', CategorySerializer) class CategoryList(APIView): permission_classes = [AllowAny] @swagger_auto_schema( manual_parameters=[username_param, email], query_serializer=CategorySerializer, responses = { '200' : category_response, '400': 'Bad Request' }, security=[], operation_id='List of categories', operation_description='This endpoint does some magic', ) def get(self, request, format=None): """ GET: Return a list of all the existing categories. """ categories = Category.objects.all() serializer = CategorySerializer(categories, many=True) return Response(serializer.data) @swagger_auto_schema( request_body=CategorySerializer, query_serializer=CategorySerializer, responses={ '200': 'Ok Request', '400': "Bad Request" }, security=[], operation_id='Create category', operation_description='Create of categories', ) def post(self, request, format=None): """ POST: Create a new category instance. """ serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save(created_by=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
###icode9 帮助文档
https://www.icode9.com/content-4-782511.html
Django 关于drf_yasg Api文档使用示例
配置
- settings.py
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="平台API文档", default_version='v1', description="Welcome to ***", # terms_of_service="https://www.tweet.org", # contact=openapi.Contact(email="demo@tweet.org"), # license=openapi.License(name="Awesome IP"), ), public=True, # 我也添加了此处但是还是有权限问题 permission_classes=(permissions.AllowAny,), )
# 对测试人员更友好 path('doc/', 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'),
测试的时候报403
#注释掉此处就可访问到文档 REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ['user_profile.utils.auth.CustomAuthentication', ], }
api文档编写使用
from drf_yasg.utils import swagger_auto_schema class PolygonView(APIView): # 使用该装饰器 @swagger_auto_schema() def get(self, request, generate_id): pass
装饰器使用前介绍
查看drf_yasg.openapi模块中的 20-56行,介绍了 type,format,in_三个参数的类型,他们值都进行了常量化
type有:
"object" ,"string" ,"number" ,"integer" ,"boolean" ,"array" ,"file"
format有:
date,date-time,password,binary,bytes,float,double,int32,int64,email,
ipv4,ipv6,uri,uuid,slug,decimal等类型
in_参数(代表参数在什么位置)有:
body,path,query,formData,header
Parameter:用来构造请求参数
Schema:对参数进行补充说明,属性说明等
Response:用来构造单个响应数据的 比如200状态码对应的响应
Responses:用来构造多个响应数据的 {200:正常响应,401:验证未通过响应}
swagger_auto_schema使用
def swagger_auto_schema(
method=None, # 单个请求方法 GET 类方法下不需要
methods=None, # 请求方法的列表 ['GET','POST'] 类方法下不需要
auto_schema=unset,
request_body=None, # 请求体 Schema对象
query_serializer=None, # serializer类
manual_parameters=None, # 参数列表 [Parameter对象列表] 可以通过in_=IN_PATH,来修饰path中的参数
operation_id=None, # API的唯一编号 可以不填
operation_description=None, # 对该API的描述信息
operation_summary=None,
security=None,
deprecated=None, # 是否弃用
responses=None, # 响应体 {200:Response对象,401:serializer类}
dict[int or str, (drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or
drf_yasg.openapi.Response or str or rest_framework.serializers.Serializer)]
field_inspectors=None,
filter_inspectors=None,
paginator_inspectors=None,
tags=None, # 模块名称
**extra_overrides):
Parameter使用
class Parameter(SwaggerDict):
def __init__(self, name, in_, description=None, required=None, schema=None,
type=None, format=None, enum=None, pattern=None, items=None, default=None, **extra):
name:参数名称
in_:参数位置 参见 装饰器使用前介绍 部分
description:参数描述
required:是否必须
schema:当in_是body时,schema对象
type:类型 参见 装饰器使用前介绍 部分
format:格式 参见 装饰器使用前介绍 部分
enum:(列表) 列举参数的请求值(请求值只在这几个值中)
pattern:当 format为 string是才填此项
items:
default:
###Schema使用
class Schema(SwaggerDict):
def __init__(self, title=None, description=None, type=None, format=None, enum=None, pattern=None, properties=None,additional_properties=None, required=None, items=None, default=None, read_only=None, **extra):
title:标题(可以不填)
description:描述
type:类型 参见 装饰器使用前介绍 部分
format:格式 参见 装饰器使用前介绍 部分
enum:(列表) 列举参数的请求值(请求值只在这几个值中)
pattern:当 format为 string是才填此项
properties: 当 type为object时,为dict对象
{'str1':Schema对象,'str2':SchemaRef对象}
required:[必须的属性列表]
items:当type是array时,填此项
default:
Response使用
class Response(SwaggerDict):
def __init__(self, description, schema=None, examples=None, **extra):
description:字符串
schema:Schema对象
examples:dict对象
PUT请求示例
polygon_view_put_desc='根据generate_id修改一个图斑'
polygon_view_put_parm=Schema(type=TYPE_OBJECT,properties={
'reason':Schema(description='变化原因 example: 造林更新',type=TYPE_STRING),
'village':Schema(description='所属乡镇 example: 石马镇',type=TYPE_STRING),
'remarks':Schema(description='备注 example: ...',type=TYPE_STRING),
'real_area':Schema(description='实测面积 example: 2020',type=TYPE_NUMBER),
'disguise_change':Schema(description='是否是伪变化 example: 0表示不是,1 表示是',type=TYPE_INTEGER,enum=[0,1]),
'images':Schema(description='上传图片id列表 example: [1,2,3]',type=TYPE_ARRAY,items=Schema(type=TYPE_INTEGER)),# 列表对象
})
polygon_view_put_resp={200:Response(description='修改成功',examples={'json':{'msg': '修改成功!', "data": []}})}
@swagger_auto_schema(operation_description=PSW.polygon_view_put_desc,request_body=PSW.polygon_view_put_parm,responses=PSW.polygon_view_put_resp)
def put(self, request, generate_id):
pass
请求参数效果图:
响应效果:
GET请求示例
polygon_view_get_desc='根据generate_id获取 返回一个图斑'
polygon_view_get_parm=[
Parameter(name='generate_id',in_=IN_PATH,description='图斑id example:20201212125560555',type=TYPE_STRING,required=True),
Parameter(name='year',in_=IN_QUERY,description='年份 example: 2020',type=TYPE_INTEGER,required=False),
Parameter(name='quarter', in_=IN_QUERY, description='季度 例如:1 代表一季度', required=False,type=TYPE_INTEGER,enum=[1,2,3,4,5]),
]
polygon_view_get_resp={200:DiffPolygonSerializer}
@swagger_auto_schema(operation_description=PSW.polygon_view_get_desc,manual_parameters=PSW.polygon_view_get_parm,responses=PSW.polygon_view_get_resp)
def get(self, request, generate_id):
pass
效果图:
标签:None,yasg,description,示例,Django,Schema,view,type,schema