Home » Django & REST Api » Using status codes in Django Response to make it better readable

Using status codes in Django Response to make it better readable

This post is in continuation with our another post “Developing REST API using functions in DRF application views” , for all posts related to Django and DRF refer to page “Django and Django-REST Framework”

As you can see in previous post, we have written the view using functions as below,

@csrf_exempt
def users(request):
    if request.method == 'GET':
        users = UserInfo.objects.all()
        serializer = UserInfoSerializer(users, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserInfoSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

Notice above, we have written the status code in numbers as “status=201” and “status=400” but since those are only numbers, in a first impression new developer will not be able to understand what those codes stands for unless he is aware of http codes.

Django provides human readable status codes with meaningful words as described in “Django REST Framework Status Codes” , so referring to this page, we changed our code with actual changes as,

+++ b/helloproject/helloapp/views.py

+from rest_framework import status
 
def users(request):
-            return JsonResponse(serializer.data, status=201)
-        return JsonResponse(serializer.errors, status=400)
+            return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
+        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

as you can see, we changed status codes from numbers i.e. “status=201” to more meaningful “status.HTTP_201_CREATED” and “status=400” to more meaningful “status.HTTP_400_BAD_REQUEST”

final code would look like,

@csrf_exempt
def users(request):
    if request.method == 'GET':
        users = UserInfo.objects.all()
        serializer = UserInfoSerializer(users, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserInfoSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Leave a Comment