我正在使用drf-spectacular为django生成一个OpenAPI模式。因为我没有使用序列化程序,所以我在extend_schema装饰器中定义了一切。现在我的问题是,是否可以手动定义组件模式。
下面是我的api视图的示例:
from rest_framework.decorators import api_view
from drf_spectacular.utils import (extend_schema, OpenApiExample)
from drf_spectacular.types import OpenApiTypes
from rest_framework.response import Response
@extend_schema(
examples=[OpenApiExample(
value=[
{'title': 'A title'},
{'title': 'Another title'},
],
)],
responses={
200: OpenApiTypes.OBJECT
}
)
@api_view(['GET'])
def list_articles(request):
return Response([{'title': 'Test1'}, {'title': 'Test2'}])并且相应的组件显示为空(例如,在swagger中):

Here是文档中的定义,但我不知道如何使用drf-spectacular来实现它。
发布于 2021-11-01 15:25:53
OpenApiTypes.OBJECT意味着响应对象可以有任意数量的字段。当然,Swagger UI不能预先知道这些字段,因此它显示{},这可能不直观,但它是正确的。
你想要的是给你的响应一些结构。壮观的一切都围绕着序列化程序/组件。如果不想使用显式序列化程序,可以使用inline_serializer创建隐式序列化程序
from drf_spectacular.utils import extend_schema, OpenApiExample, inline_serializer
@extend_schema(
examples=[OpenApiExample(
value=[
{'title': 'A title'},
{'title': 'Another title'},
],
)],
responses={
200: inline_serializer(
name='Article',
fields={
'title': serializers.CharField(),
}
)
}
)
@api_view(['GET'])
def list_articles(request):
passhttps://stackoverflow.com/questions/69482097
复制相似问题