djangodjango-rest-frameworkdrf-yasg

How can I customize drf-yasg endpoints's example response?


on my Django project, I'm using DRF and drf-yasg. At some endpoint, the example response body shows the incorrect example. like the following example: enter image description here

But some of them don't show the correct example response body.enter image description here

This endpoint actually returns access_token and refresh_token, doesn't return the email and password. It's wrong information for the front-end devs. Is there any way to change this?


Solution

  • Below is an example using @swagger_auto_schema annotation with 3 serializers. 1 request serializer and 2 response serializers (success and error serializers).

    class RequestSerializer(serializers.Serializer):
       param = serializers.CharField()
    
                      
    class SucessSerializer(serializers.Serializer):
       success = serializers.BooleanField()
       message = serializers.CharField()
    
                         
    class ErrorSerializer(serializers.Serializer):
       success = serializers.BooleanField()
       errors = serializers.IntegerField()
    

    class ExampleViewView(APIView):
    
        @swagger_auto_schema(
            request_body = RequestSerializer,
            responses={
                '200': SucessSerializer,
                '500': ErrorSerializer,
            },
            operation_description = 'Doc description'
        )
        def post(self, request):
            
            return successResponse({
                'sucess': True
            })