Join my Laravel for REST API's course on Udemy 👀

Return JSON response from a Django view

March 25, 2021  ‐ 2 min read

When making an API with Django I go straight to Django REST framework. However, you don't need it at all to just return a JSON response from Django.

When you are rendering a template in Django your view probably returns an instance of the HttpResponse class. It is a common way to print some text on a webpage:

from django.http import HttpResponse


def index(request):
    return HttpResponse('Just rendering a string :)')

If you invoke the render shortcut function you are actually returning a HttpResponse too. The render function renders the template file to a string and returns a HttpResponse with the rendered template as its content.

from django.shortcuts import render


def index(request):
    return render(request, 'blog/index.html')

Besides HttpResponse Django comes with a JsonResponse class as well. This JsonResponse is actually a subclass of HttpResponse. The JsonResponse transforms the data you pass to it to a JSON string and sets the content type HTTP header to application/json.

To return JSON data from a Django view you swap out the HttpResponse for JsonResponse and pass it the data that needs to be transformed to JSON.

from django.http import JsonResponse


def index(request):
    return JsonResponse({'text': 'Just rendering some JSON :)'})