DRF response doesn't have json method but it's used

Viewed 146

I have a situation that I don't understand, if I do something like that in my tests, returning this object:

response = Response()
response.status_code = 200
response.data = json.dumps({'bla': 'test_bla'})

I can check it and:

response.data # works
response.json() # doesn't

I see the doc and I don't see it has the method 'json'

2 Answers

rest_framework.Response (which does not have a json() method) and urllib3.HTTPResponse (which does have a json() method) are not the same response object :

  • rest_framework.Response is used to build a response on your views.
  • urllib3.HTTPResponse is used when an HTTP query is performed.

urllib3.HTTPResponse is also often found on unit tests (through DRF APIClient) or remote HTTP queries, that's may be why you can see it on some examples. It might be the reason why you might think that rest_framework.Response should have a json() method but does not.

With this, you can use the response.json()

import requests

response = requests.models.Response()
response.status_code = 200
response._content = (json.dumps(content)).encode('utf-8')
Related