How to change status of JsonResponse in Django

PythonPython 3.xDjangoPython 2.7Tastypie

Python Problem Overview


My API is returning a JSON object on error but the status code is HTTP 200:

response = JsonResponse({'status': 'false', 'message': message})
return response

How can I change the response code to indicate an error?

Python Solutions


Solution 1 - Python

JsonResponse normally returns HTTP 200, which is the status code for 'OK'. In order to indicate an error, you can add an HTTP status code to JsonResponse as it is a subclass of HttpResponse:

response = JsonResponse({'status':'false','message':message}, status=500)

Solution 2 - Python

Return an actual status

JsonResponse(status=404, data={'status':'false','message':message})

Solution 3 - Python

Python built-in http library has new class called HTTPStatus which is come from Python 3.5 onward. You can use it when define a status.

from http import HTTPStatus
response = JsonResponse({'status':'false','message':message}, status=HTTPStatus.INTERNAL_SERVER_ERROR)

The value of HTTPStatus.INTERNAL_SERVER_ERROR.value is 500. When someone read your code it's better define someting like HTTPStatus.<STATUS_NAME> other than define an integer value like 500. You can view all the IANA-registered status codes from python library here.

Solution 4 - Python

To change status code in JsonResponse you can do this :

response = JsonResponse({'status':'false','message':message})
response.status_code = 500
return response

Solution 5 - Python

This answer from Sayse works but it's undocumented. If you look at the source you find that it passes the remaining **kwargs to the superclass constructor, HttpStatus. However in the docstring they don't mention that. I don't know if it's the convention to assume that keyword args will be passed to the superclass constructor.

You can also use it like this:

JsonResponse({"error": "not found"}, status=404)

I made a wrapper:

from django.http.response import JsonResponse

class JsonResponseWithStatus(JsonResponse):
    """
    A JSON response object with the status as the second argument.

    JsonResponse passes remaining keyword arguments to the constructor of the superclass,
    HttpResponse. It isn't in the docstring but can be seen by looking at the Django
    source.
    """
    def __init__(self, data, status=None, encoder=DjangoJSONEncoder,
                 safe=True, json_dumps_params=None, **kwargs):
        super().__init__(data, encoder, safe, json_dumps_params, status=status, **kwargs)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDhanushka AmarakoonView Question on Stackoverflow
Solution 1 - PythonSelcukView Answer on Stackoverflow
Solution 2 - PythonSayseView Answer on Stackoverflow
Solution 3 - PythonKushan GunasekeraView Answer on Stackoverflow
Solution 4 - PythonPratik GujarathiView Answer on Stackoverflow
Solution 5 - PythonBenjamin AtkinView Answer on Stackoverflow