Last modified: Jan 10, 2023 By Alexander Williams

How to use Django JsonResponse with example

JsonResponse is a subclass that helps us to create a JSON-encoded response. In this tutorial, we'll see how to use JsonResponse and Why we need JsonResponse?

Django version and starcture

Django version

In this tutorial, we will work with Django == 4.0. This example may not be working under 2.0.

Project starcture

pytutorial
    ├── db.sqlite3
    ├── manage.py
    ├── polls
    │   ├── admin.py
    │   ├── apps.py
    │   ├── __init__.py
    │   ├── migrations
    │   ├── models.py
    │   ├── __pycache__
    │   ├── tests.py
    │   └── views.py
    └── pytutorial
        ├── asgi.py
        ├── __init__.py
        ├── __pycache__
        ├── settings.py
        ├── urls.py
        └── wsgi.py

JsonResponse in an example

In polls/views.py, we'll import JsonResponse. Then we'll write a simple view.

from django.shortcuts import render
from django.http import JsonResponse

# Create your views here.

def json_response(request):

    # Data
    d = {"message":"Hello JsonResponse"}

    # JsonResponse
    return JsonResponse(d)

The json_response view: return data {"message":"Hello JsonResponse"} as JSON.

In pytutorial/urls.py, Let's create a path for the json_response view.

from django.contrib import admin
from django.urls import path
# Views
from polls.views import json_response

urlpatterns = [
    path('admin/', admin.site.urls),
    #
    path("json/", json_response)
]

To test the view, we need to open http://localhost:8000/json/ on a browser.

JsonResponse

As you can see in the image, we've got a JSON response.

Why we need JsonResponse

JsonResponse helps us to:

  • Build a single page application
  • Build API application

In  polls/views.py, we'll write a simple API that sends the capital of a given country name.

from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from countryinfo import CountryInfo

# Create your views here.

@csrf_exempt
def capital_api(request):
    if request.method == "POST":
        # Country's name
        country = request.POST.get('country')
        # Capital
        capital = CountryInfo(country).capital()
        # Send Capital as JSON
        return JsonResponse({"capital":capital})
    
    return JsonResponse({"Output":"Capital API"})

First of all, we've added @csrf_exempt to the top of our views to avoid the token. Then got the country name from the request. Then used the countryinfo library to get the capital of a country. Finally, we've returned the capital as JSON.

In pytutorial/urls.py, we need to add a path for capital_api view.

from django.contrib import admin
from django.urls import path
# Views
from polls.views import json_response, capital_api

urlpatterns = [
    path('admin/', admin.site.urls),
    #
    path("json/", json_response),
    #
    path('capital-api/', capital_api)
]

Now, Let's test our API outside of the project.

import requests

# Request
req = requests.post("http://localhost:8000/capital-api/", {"country":"united states"})

# Response
print(req.text)

Output:

{"capital": "Washington D.C."}

As you can see, we got the capital of United States as JSON and we can parse it by using the json.loads() method.