shreesh katti
shreesh katti

Reputation: 837

What is difference between JsonResponse and HttpResponse in django

Lets say result = {'a': 1, 'b': 2, 'c': 3}

Is there a difference between these two:

return HttpResponse(json.dumps(a))

and

return JsonResponse(a)

Upvotes: 8

Views: 14909

Answers (4)

Amrit Prasad
Amrit Prasad

Reputation: 427

  • HTTPResponse

    • HTTPResponse (content=response body, content_type=response body data type, status=status code)
    • Suitable for string, templates
    • class HttpResponse(HttpResponseBase):
  • JsonReponse

    • It is a subclass of HTTPResponse,
      • Suitable for processing data in json format, but can not return templates.
      • class JsonResponse(HttpResponse):

Refer Django Doc

Upvotes: 0

Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3964

Try this it will pass

return HttpResponse(json.dumps("abcd"))

But if you do

return JsonResponse("abcd")

JsonResponse will give you TypeError if you send non serializable data (Unless safe=False in JsonResponse)

So it is safer to send json data in JsonResponse

And in header JsonResponse will set Content-Type: application/json on the other hand HttpResponse will set Content-Type: text/html; charset=utf-8

Upvotes: 3

Slam
Slam

Reputation: 8572

As doc states, main difference is

  • automatic serialization
  • proper content type
  • safer input check by default

Upvotes: 8

TechSavy
TechSavy

Reputation: 1340

Django uses request and response objects to pass state through the system. Each view is responsible for returning an HttpResponse object. Using HttpResponse you need to first serialize your object to JSON.

Whereas,

Since version 1.7, Django counts with the built-in JsonResponse class, which is a subclass of HttpResponse. Its default Content-Type header is set to application/json, which is really convenient. It also comes with a JSON encoder, so you don’t need to serialize the data before returning the response object.

You can also refer this doc:

Upvotes: 4

Related Questions