drf-spectacular: Specify empty payload using @extend_schema
Asked Answered
C

1

7

Consider that I have a simple view as,

# serializers.py
class EmptyPayloadResponseSerializer(serializers.Serializer):
    detail = serializers.CharField()


# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from drf_spectacular.utils import extend_schema
from .serializers import EmptyPayloadResponseSerializer


class EmptyPayloadAPI(APIView):
    @extend_schema(responses=EmptyPayloadResponseSerializer)
    def post(self, request, *args, **kwargs):
        # some actions
        return Response(data={"detail": "Success"})

When I render the schema, I have got the following error response,

Error #0: EmptyPayloadAPI: unable to guess serializer. This is graceful fallback handling for APIViews. Consider using GenericAPIView as view base class, if view is under your control. Ignoring view for now.

So, how can I tell to @extend_schema decorator that I'm intended to pass nothing as payload?

Corrigan answered 22/5, 2021 at 12:9 Comment(0)
C
8

Settings request=None in the @extend_schema(...) decorator will do the trick!!!

class EmptyPayloadAPI(APIView):
    @extend_schema(request=None, responses=EmptyPayloadResponseSerializer)
    def post(self, request, *args, **kwargs):
        # some actions
        return Response(data={"detail": "Success"})
Corrigan answered 22/5, 2021 at 12:9 Comment(3)
While valid, this could cause issues with auto-generated clients. Setting request=None will remove the requestBody section from the schema. My auto-generated Java openapi-generator/5.4.0 client failed because it expected Content-Type to be defined inside the requestBody section on all POST/PUT/PATCH requests.Mump
Have you tried to use the native swagger engine to build the UI from the specification? and does that have the problem you've mentioned?Corrigan
Creating the client with swagger-codegen/3.0.33 failed to build similar to this issue.Mump

© 2022 - 2024 — McMap. All rights reserved.