7

I'm trying to create a custom API (not using models), but its not showing the request definition in the schema (in consequence, not showing it in swagger). My current code is:

views.py

class InfoViewSet(viewsets.ViewSet):

    @list_route(methods=['POST'])
    def some_method(self, request):
       data = JSONParser().parse(request)
       serializer = GetInfoSerializer(data=data)
       serializer.is_valid(raise_exception=True)
       info = get_data_from_elsewhere(serializer.data)
       return Response(info)

urls.py

router.register(r'^info', InfoViewSet, base_name='info')

serializers.py

class InfoSomeMethodSerializer(serializers.Serializer):

  list_id = serializers.ListField(child=serializers.IntegerField())
  password = serializers.CharField()

And it appears in swagger, but just the response part. How can I register the post parameters? I'm also not sure if I'm using DRF correctly (I'm new) so any correction will be appreciated.

--

edit: I tried the serializer_class argument suggested by Linovia and didn't work, I got:

TypeError: InfoViewSet() received an invalid keyword 'serializer_class'

I tried overriding get_serializer_class method and didn't work either:

def get_serializer_class(self):
    if self.action == 'some_method':
        return InfoSomeMethodSerializer
Aneesh R S
  • 3,807
  • 4
  • 23
  • 35
Ed_
  • 368
  • 1
  • 4
  • 22
  • 1
    `self.action in ['list', 'retrieve']`. As far as I know you can not provide `some_method` directly. Example in the answer here. https://stackoverflow.com/questions/22616973/django-rest-framework-use-different-serializers-in-the-same-modelviewset – joe Mar 23 '18 at 07:40

1 Answers1

2

For people running this into the future - when you add the serializer_class attribute to the @action decorator of a view which inherits from viewsets.ViewSet, it will indeed by default give you a TyperError, as OP mentioned:

TypeError: InfoViewSet() received an invalid keyword 'serializer_class'

To overcome this, simply add serializer_class = None as a class variable to your view.

Example of editing OPs code:

class InfoViewSet(viewsets.ViewSet):
    # ↓ ADD THIS!
    serializer_class = None 

    # Now you can add serializer_class without geting a TypeError ↓
    @list_route(methods=['POST'], serializer_class=GetInfoSerializer)
    def some_method(self, request):
       data = JSONParser().parse(request)
       serializer = GetInfoSerializer(data=data)
       serializer.is_valid(raise_exception=True)
       info = get_data_from_elsewhere(serializer.data)
       return Response(info)
Ulm
  • 277
  • 2
  • 8