6

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!

Ahmadreza
  • 939
  • 1
  • 9
  • 13
  • Why would you override a function? That seems like it is asking for trouble. –  Mar 23 '18 at 20:22
  • @TheOneWhoⱽᴱᴿᴮ Like I said, because I want to return the custom response. Take look at the return statement of the list function; the default is "return Response(serializer.data)" – Ahmadreza Mar 23 '18 at 20:47

2 Answers2

3

First import these packages/modules.

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework import status

The below code use just above your function view as decorators

login_schema = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'usernmae': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
        'password': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
    },
    required=['username', 'password']
)
login_schema_response = {
    status.HTTP_200_OK: openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
           'students': openapi.Schema(type=openapi.TYPE_OBJECT)
        }
    ),
    status.HTTP_201_CREATED: openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
           'students': openapi.Schema(type=openapi.TYPE_OBJECT)
        }
    ),
}

@swagger_auto_schema(method='post', request_body=login_schema, responses = login_schema_response)
def myAccount(request):
     pass

Here, I have stored request and response schema object in a different variable.

Sumit Kumar Gupta
  • 2,132
  • 1
  • 22
  • 21
2

Try the following code:

@swagger_auto_schema(responses={
    status.HTTP_200_OK: Schema(
        type=TYPE_OBJECT,
        properties={
           'students': Schema(
              type=TYPE_ARRAY
           )
        }
    )
})