django - 使用 drf-spectacular 为 django API 定义组件模式

标签 django django-rest-framework openapi drf-spectacular

我正在使用 drf-spectacular 为 django 生成一个 OpenAPI 模式。因为我没有使用序列化程序,所以我在 extend_schema 装饰器中定义了所有内容。现在我的问题是,是否可以手动定义组件架构。

这是我的 api View 的示例:

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 中):

swagger-ui example of empty component

Here是文档中的定义,但我无法弄清楚如何使用 drf-spectacular 实现它。

最佳答案

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):
    pass

关于django - 使用 drf-spectacular 为 django API 定义组件模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69482097/

相关文章:

python - 如何在python中上传文件时读取内存中zip文件的内容?

python - 检查 django 权限或运算符(operator)?

c# - 如何从 swagger.json 中删除反引号

swagger-ui - Swagger UI 文档页面前端的凭据存储在哪里?

django+nginx+uwsgi,文件浏览器不上传

python - Django rest framework Router - 如何添加自定义 URL 和 View 功能

python - 注释字段上的 django-filter 过滤器

Django-Rest-Framework - 嵌套对象和序列化器,如何?

python - Django 休息 : The view does not want to import

java - 从 Swagger/OpenAPI 生成 Spring MVC Controller