drf-yasg icon indicating copy to clipboard operation
drf-yasg copied to clipboard

Responses with Nested Serializers

Open jamesstonehill opened this issue 1 year ago • 0 comments

Feature Request

I'd like to be able to nest serializers within the response documentation under string keys.

Description

In my api, all of our responses are nested under a "data" key like so:

{
  "data": {
    "first_name": "Foo",
    "email": "[email protected]"
  },
  "message": "User account successfully created!"
}

To achieve this response the routes return responses that look something like this...

        return Response(
            ResponseSerializer(
                dict(
                    data=UserSerializer(user).data,
                    message="User account successfully created!",
                )
            ).data,
            status=status.HTTP_200_OK,
        )

Describe the solution you'd like

I'd like to be able to do this:

USER_RESPONSES = {
    200: {
        "data": UserSerializer(),
        "message": "User account successfully created!"
    }
}

However that doesn't work, so I'm forced to manually write out all the attributes within the UserSerializer again within the documentation.

Describe alternatives you've considered

Are there any workarounds? I've investigated, but I haven't been able to find any good options for how to achieve this behaviour.

jamesstonehill avatar Nov 08 '22 13:11 jamesstonehill