jorilallo
jorilallo

Reputation: 788

Combining request.data and request.query_params in Django REST Framework

I'm using DRF to build a RPC-style API where each endpoint can be called with either GET or POST method. So far I got the methods combined nicely:

class UpdateUser(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        return self.get(request, *args, **kwargs)

    def get(self, request, format=None):
        # Do stuff here with request.data

Unfortunately POST provides data in request.data and GET in request.query_params. Is there a way to combine them both into request.data or something custom like request.params? Parsers doesn't seem to work as they aren't being called on GET requests.

Upvotes: 3

Views: 20726

Answers (1)

AKS
AKS

Reputation: 19861

I agree with @jorilallo' comments about using request.data inside get function.

Alternatively, what you could do is create another function in the view which can have either request.data or request.query_params as arguments:

class UpdateUser(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        # POST have request.data 
        return self.process_request(request, request.data)

    def get(self, request, format=None):
        # GET have request.query_params
        return self.process_request(request, request.query_params)

    def process_request(self, request, data):
        # Do stuff here with data
        # return a response

Here, process_request function is called from both post and get methods and relevant data is passed as arguments.

Upvotes: 9

Related Questions