可以'Append new request example to drf-spectacular schema”翻译成“将新的请求示例附加到drf-spectacular模式”,解决方法如下:
示例视图函数:
from drf_spectacular.utils import extend_schema
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.plumbing import build_request_serializer
from rest_framework.decorators import schema
class ExampleView(APIView):
@extend_schema(
request=build_request_serializer(
types={'application/json': OpenApiTypes.OBJECT},
required=['field1', 'field2'],
properties={'field1': {'type': 'string', 'example': 'example1'},
'field2': {'type': 'integer', 'example': 123}}
)
)
def post(self, request):
pass
这里使用build_request_serializer
来生成请求参数的Schema。在properties
参数中,我们可以设置每个属性的类型、描述和示例。
在视图方法上,我们使用@extend_schema
来扩展Schema。这里,我们使用了build_request_serializer
生成了一个请求参数的Schema,并将其作为请求对象的一部分添加到了扩展的Schema中。
这样,在生成OpenAPI文档时,我们就可以在请求对象的Schema中看到示例参数。
示例输出:
openapi: '3.0.3'
info:
title: My API
version: 1.0.0
paths:
/example/:
post:
requestBody:
content:
application/json:
schema:
type: object
properties:
field1:
type: string
example: example1
field2:
type: integer
example: 123
required:
- field1
- field2
responses:
'200':
description: ''
在requestBody
节点下,我们可以看到请求对象的Schema,其中包含了示例参数