Drf-yasg: How to change input and return Serializer

Created on 1 May 2019  路  2Comments  路  Source: axnsan12/drf-yasg

Most of my APIs input and outputs are different 馃憤
An example:
Input is {'A':1, 'B':2} and returns {A:{B:[1,2,3,4]}, }

The API works correctly, but the documentation page shows both the same as input (data)

How can I configure that?

question

Most helpful comment

Yes, that is the simplest approach for this case.

A more DRY approach would be defining your own RequestResponseAPIView which would have separate request_serializer_class and response_serializer_class fields and using a custom SwaggerAutoSchema to inspect those fields, but short of doing that you're stuck manually decorating methods, since DRF by default does not distinguish request/response serializers.

All 2 comments

Just figured out the supported approach! You'll have to decorate the desired method/function with swagger_auto_schema decorator.
The usage would look something like this:

@swagger_auto_schema(responses={201: serializers.SerializerB()})
def create(self, request, *args, **kwargs):
    in_serializer = self.get_serializer(data=request.data) #this should give you a SerializerA instance
    ... # your custom business logic goes here
    out_serializer = serializers.SerializerB(data)
    return response.Response(out_serializer.data, status=201)

Yes, that is the simplest approach for this case.

A more DRY approach would be defining your own RequestResponseAPIView which would have separate request_serializer_class and response_serializer_class fields and using a custom SwaggerAutoSchema to inspect those fields, but short of doing that you're stuck manually decorating methods, since DRF by default does not distinguish request/response serializers.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jaumard picture jaumard  路  5Comments

phihag picture phihag  路  3Comments

csdenboer picture csdenboer  路  3Comments

beaugunderson picture beaugunderson  路  5Comments

marcosgeorgopoulos picture marcosgeorgopoulos  路  4Comments