drf-spectacular:将 OpenApiResponse 添加到无序列化程序的基于函数的视图

drf-spectacular: Add OpenApiResponse to a serializer-less function-based view

所以, 我正在使用 drf-spectacular:

记录以下代码
from rest_framework import response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework import status

from drf_spectacular.utils import extend_schema, OpenApiParameter

def passcode_generator:
    return 0 # placeholder


@extend_schema(
    parameters=[
        OpenApiParameter(name="callsign", required=True, type=str),
    ],
    description="Get an APRS-IS passcode for a given callsign",
)
@api_view(["POST"])
@permission_classes([AllowAny])
def get_passcode(request):
    callsign = request.data.get("callsign", None)
    if callsign is None:
        raise Response(
            {"error": "Missing callsign"}, status=status.HTTP_400_BAD_REQUEST
        )
    return Response({"passcode": passcode_generator(callsign)})

我无法理解的是如何记录回复。即,drf_spectacular.utils 中有 OpenApiResponse,但文档非常薄。我如何使用此系统记录我的 API 的回复?

如果您没有 Serializer,您可以使用 inline_serializer:

from drf_spectacular.utils import extend_schema, OpenApiParameter, inline_serializer

# ...

@extend_schema(
    parameters=[
        OpenApiParameter(name="callsign", required=True, type=str),
    ],
    description="Get an APRS-IS passcode for a given callsign",
    responses={
       200: inline_serializer(
           name='PasscodeResponse',
           fields={
               'passcode': serializers.CharField(),
           }
       ), 
       400: OpenApiResponse(description='Missing callsign'),
    }
)
@api_view(["POST"])
@permission_classes([AllowAny])
def get_passcode(request):
    callsign = request.data.get("callsign", None)
    # ...