sila
sila

Reputation: 179

Can we have multiple get method in apiview class django rest framework

Am using django rest framework with apiviews. I'd like to use multiple get method in the apiview class and seperate with the name of the medthod in the urls file.

Upvotes: 6

Views: 4659

Answers (1)

Pankaj Saini
Pankaj Saini

Reputation: 800

You can use viewsets instead of apiview for this purpose.

Here's an example.

from rest_framework import viewsets
from rest_framework.decorators import detail_route
from rest_framework.response import Response

class MyViewSet(viewsets.GenericViewSet):

    @detail_route(methods=['get'])
    def some_get_method(self, request, pk=None):
        return Response({'data': 'response_data'})

In order to use it, your URL will be like, http://base_url/< pk >/some_get_method

or you can override dispatch method inside of APIView to do so,

def MyAPIView(APIView):
    def some_get_method(self, request):
        return Response({'data': 'response_data'})

    def dispatch(self, request, *args, **kwargs):
        if request.method.lower() == "get" and request.GET.get('identifier'):
            return self.some_get_method(request)
        return super().dispatch(request, *args, **kwargs)

Upvotes: 5

Related Questions