How to use JsonResponse in Django?

Published On: 05/09/2022 | Category: Django


Hi Dev,

Are you looking for example of how to use django jsonresponse. you can see how to use jsonresponse in django. you can understand a concept of django jsonresponse get data. This article goes in detailed on return json response django view. Follow bellow tutorial step of how to create jsonresponse in django.

In JsonResponse is a subclass that helps us to create a JSON-encoded response. so in this example, we'll see how to create JsonResponse and why we need JsonResponse?

Here i explained simply step by step example of how to use django JsonResponse.

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

Example : 1

In this example i hope you have already created a core app In core/views.py, we'll import JsonResponse. Then we'll write a simple view.

core/views.py
from django.shortcuts import render
from django.http import JsonResponse

# Create your views here.

def json_response(request):

    # Data
    d = {"message":"Welcome to Tuts-Station.com"}

    # JsonResponse
    return JsonResponse(d)

The json_response view: return data {"message":"Welcome to Tuts-Station.com"} as JSON.

{
    "message": "Welcome to Tuts-Station.com"
}
Example : 2

In this second example we will discuss about why we need jsonresponse, JsonResponse helps us to create a single page application, and create a API application so let's see the example.

core/views.py
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"})

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.

Next, Let's get 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)
{"capital": "Washington D.C."}

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

I hope it will help you....