14

How to access GET request data in django rest framework. In the docs, they have mentioned "For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET"

https://www.django-rest-framework.org/api-guide/requests/

But when I use request.query_params.get('some_vaue') it gives me none even though I pass the data in the request body.

sample code example:

class TestView(APIView):
    def get(self, request):
        test = request.query_params.get('test')
        print('data',test)
        ...
        ...
        ...

When I pass some value in the body of the request in postman and print the value, it actually prints None.

Update

Below is my axios code

 axios.get(API_URL, {
            headers: {
                'Content-Type': 'application/json'
            },
            params: {
                page_num: 1, 
                test: 'test data'
            }
        })
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            console.log(err.response.data);
        });

Re-Update:

For testing purpose I printed out the request object like

print(request.__dict__)

so it printed out

{'_request': <WSGIRequest: GET '/api/my api url/?page_num=1&test=test+data'>, 'parsers': [<rest_framework.parsers.JSONParser object at 0x0000016742098128>, <rest_framework.parsers.FormParser object at 0x00000167420980B8>, <rest_framework.parsers.MultiPartParser object at 0x00000167420980F0>], 'authenticators': (), 'negotiator': <rest_framework.negotiation.DefaultContentNegotiation object at 0x0000016742098080>, 'parser_context': {'view': <app_name.views.APIClassName object at 0x0000016742280400>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request object at 0x0000016742107080>, 'encoding': 'utf-8'}, '_data': {}, '_files': <MultiValueDict: {}>, '_full_data': {}, '_content_type': <class 'rest_framework.request.Empty'>, '_stream': None, 'accepted_renderer': <rest_framework.renderers.JSONRenderer object at 0x00000167421070B8>, 'accepted_media_type': 'application/json', 'version': None, 'versioning_scheme': None, '_authenticator': None, '_user': <django.contrib.auth.models.AnonymousUser object at 0x0000016741FFAC88>, '_auth': None}

I could see that it is passing the data but not sure why if i do request.data['page_num'] or any other value it doesn't get the data.

3 Answers 3

18

If you are using class based views :

POST provides data in request.data and GET in request.query_params

If you are using function based views:

request.data will do the work for both methods.

axios does not support sending params as body with get method , it will append params in url. so if you are using axios you will have to use query_params

Axios example code:

axios.get(API_URL, {
            params: {
                testData: 'test data',
                pageNum: 1
            }
        })
        .then(res => {
            console.log(res);
        })
        .catch(err => {
            console.log(err.response.data);
        });

DRF example code:

Class TestView(APIView):
    def get(self, request):
        test_data_var = request.query_params['testData']
        page_num_var = request.query_params['pageNum']

Note: If you're testing it in postman then put the get request query params in Params tab.

Sign up to request clarification or add additional context in comments.

45 Comments

Yes that works fine in postman if I use request.data['test']. But when I use axios to send a get request with some data in the body, it actually gives KeyError exception. when printed out the request.data it was actually a blank object. But when i tried request.GET.get('test') I was able to get the data.
backend api is never depends on which api plugin you are using for fronted @AashayAmballi
in axios you will have to mention the method as well @AashayAmballi .
Yes, the same thing doesn't work if I pass the data from Axios.
I have mentioned the method. I'll update the axios code in my question
|
0

For me the accepted answer did not work.

A much simplier solution I saw no one mention is the following :

Append them to the URL like this : yourApi.com/subdomain/?parameter1=something

  • Axios.js
const target = "someApiYouWantToFetch.com"
let parameter = "DataYouWantToSend"
axios.get(`${target}?parameter=${parameter }`)
  • views.py
def get(self,request,*args,**kwargs): #or def list()
    data = request.GET.get('name')

1 Comment

It's not best practice to use Django's request.GET.get in Django Rest Framework. As it's mentioned in the official documentation. django-rest-framework.org/api-guide/requests/#query_params and In Axios, as your params grow the harder it will be to read the URL if you just keep appending those to your URL. So it's better to pass those parmas values as an object.
0

In DRF if you want to access request.GET you should use request.request.GET

for example

@action(methods=['GET',], detail=False)
def activation(request, *args, **kwargs):
    uid = request.request.GET.get('uid')
    token = request.request.GET.get('token')

2 Comments

It's not best practice to use Django's request.GET.get in Django Rest Framework. As it's mentioned in the official documentation. django-rest-framework.org/api-guide/requests/#query_params.
I know but some times request.data doesn't work so you need to use this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.