Testing JSON Responses

A snippet showing how to test JSON responses in Django.


# models.py

from django.db import models

class Stat(models.Model):
    key = models.CharField(max_length=50)
    value = models.IntegerField(default=0)
      

# admin.py

from django.contrib import admin
from .models import Stat

@admin.register(Stat)
class StatAdmin(admin.ModelAdmin):
    list_display = ("key", "value")
      

# Result (tests/test_json.py)
from django.test import TestCase
from django.urls import reverse
import json

class JsonViewTest(TestCase):
    def test_returns_json(self):
        res = self.client.get(reverse("stats-json"))
        self.assertEqual(res.status_code, 200)
        data = res.json()
        self.assertIn("stats", data)
      
Explanation:
  • Use response.json() to parse JSON directly (Django ≥ 3.2).
  • Assert keys and value formats in the payload.
  • Category Testing
  • Total Views 697
  • Last Modified 10 March, 2026
  • Tags #testing #json #response #api
Previous snippet
Testing with Fixtures
Next snippet
Testing File Uploads
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.