Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET Body is not being sent with APIClient Django DRF

i want to send body data using get request in the django drf test case APITestCase

for example

data ={'hi':'bye'}
self.client.get('media_list/', {'body': data})

and in the views i can able get the body using below code

request.data.get('hi', None)

but it is not working using {'body': data} my test method but it is working fine in the postman raw type.

what is tried is(not working)

self.client.get('media_list/', data=data)
like image 656
karnataka Avatar asked Jan 25 '23 09:01

karnataka


1 Answers

I faced this issue while writing unit test. You can solve it with this workaround.

Problem: When you request with client.get method, the method put your data to url. You can see link in the below.
https://github.com/encode/django-rest-framework/blob/master/rest_framework/test.py#L194

Solution: You should use client.generic() directly. Don't use client.get() https://github.com/encode/django-rest-framework/blob/master/rest_framework/test.py#L203

Example

import json
from rest_framework.test import APIClient
from rest_framework.test import APITestCase


class TestClass(APITestCase):
    def setUp(self):
        # Setup run before every test method.
        pass

    def test_send_json_in_body(self):
        data ={'hi' : 'bye'}
        resp = self.client.generic(method="GET", path="/return/data/", data=json.dumps(data), content_type='application/json')

request._request
<WSGIRequest: GET '/return/data/'>
request.data
{'hi': 'bye'}

It works :)

like image 82
Aziz F Dagli Avatar answered Jan 29 '23 10:01

Aziz F Dagli