Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest swagger_auto_schema customize response body

I've overridden the list function from django rest viewset to customize the response body (it returned an json array, I wanted to return an object that contains the array) I want to put this response in swagger doc too! I use drf_yasg app in django. I've written this code:

from drf_yasg.openapi import Schema, TYPE_OBJECT, TYPE_STRING, TYPE_ARRAY
from drf_yasg.utils import swagger_auto_schema
class StudentViewSet(viewsets.ModelViewSet):
    @swagger_auto_schema(responses={200: Schema(type=TYPE_OBJECT)})
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response({'students': serializer.data})

I don't know how to give my response object description to the Schema object. I've searched so much but I found nothing useful!

like image 365
AhmadReza Avatar asked Oct 16 '22 20:10

AhmadReza


1 Answers

Try the following code:

@swagger_auto_schema(responses={
    status.HTTP_200_OK: Schema(
        type=TYPE_OBJECT,
        properties={
           'students': Schema(
              type=TYPE_ARRAY
           )
        }
    )
})
like image 182
Max Yakovenko Avatar answered Oct 20 '22 22:10

Max Yakovenko