Django JSON APIs
Not every client wants HTML. Mobile apps, single-page JavaScript front ends (React, Vue, Angular) and other servers want JSON. Plain Django can serve a clean JSON API with JsonResponse and a few conventions — no extra packages needed. (For large APIs, Django REST Framework adds serializers, authentication and browsable docs.)
JsonResponse
JsonResponse serialises a dictionary to JSON and sets Content-Type: application/json. It uses DjangoJSONEncoder, which also understands dates, decimals and UUIDs:
import sys, types, django, datetime, decimal
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import JsonResponse
from django.urls import path
from django.test import Client
def product(request):
return JsonResponse({
"id": 7,
"name": "Ceramic mug",
"price": decimal.Decimal("8.90"),
"added": datetime.date(2026, 5, 1),
"tags": ["kitchen", "gift"],
})
def tags(request):
return JsonResponse(["kitchen", "gift", "office"], safe=False) # lists need safe=False
urls.urlpatterns = [path("api/product/", product), path("api/tags/", tags)]
c = Client()
r = c.get("/api/product/")
print(r["Content-Type"])
print(r.content.decode())
print(r.json()["price"])
print(c.get("/api/tags/").json())application/json
{"id": 7, "name": "Ceramic mug", "price": "8.90", "added": "2026-05-01", "tags": ["kitchen", "gift"]}
8.90
['kitchen', 'gift', 'office']
Decimals become strings (to avoid float rounding) and dates become ISO strings. The safe=False flag is required for anything other than a dict — a historical safeguard against an old JSON-hijacking attack.
A read API for a model
Turn model objects into dictionaries yourself — that way you decide exactly which fields are public. values() is a quick way, or write a small to_dict() helper:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.urls import path
from django.test import Client
class Book(models.Model):
title = models.CharField(max_length=100)
year = models.IntegerField()
internal_notes = models.TextField(blank=True) # must NOT be exposed
class Meta:
app_label = "demo"
def to_dict(self):
return {"id": self.pk, "title": self.title, "year": self.year}
with connection.schema_editor() as editor:
editor.create_model(Book)
for t, y in [("Kindred", 1979), ("Beloved", 1987), ("Parable of the Sower", 1993)]:
Book.objects.create(title=t, year=y, internal_notes="supplier: ACME")
def book_list(request):
qs = Book.objects.order_by("year")
if "after" in request.GET:
qs = qs.filter(year__gt=int(request.GET["after"]))
return JsonResponse({"count": qs.count(), "results": [b.to_dict() for b in qs]})
def book_detail(request, pk):
return JsonResponse(get_object_or_404(Book, pk=pk).to_dict())
urls.urlpatterns = [path("api/books/", book_list), path("api/books/<int:pk>/", book_detail)]
c = Client()
print(c.get("/api/books/").json())
print(c.get("/api/books/", {"after": 1980}).json())
print(c.get("/api/books/2/").json())
print(c.get("/api/books/42/").status_code){'count': 3, 'results': [{'id': 1, 'title': 'Kindred', 'year': 1979}, {'id': 2, 'title': 'Beloved', 'year': 1987}, {'id': 3, 'title': 'Parable of the Sower', 'year': 1993}]}
{'count': 2, 'results': [{'id': 2, 'title': 'Beloved', 'year': 1987}, {'id': 3, 'title': 'Parable of the Sower', 'year': 1993}]}
{'id': 2, 'title': 'Beloved', 'year': 1987}
404
Accepting JSON: create, update, delete
API clients usually send JSON bodies, not form data. Parse request.body with json.loads, validate (a Django form is great for that), and answer with proper status codes. API views called by non-browser clients are often exempted from CSRF with @csrf_exempt — only do this when they authenticate with tokens, not cookies:
import sys, types, json, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django import forms
from django.db import models, connection
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.urls import path
from django.test import Client
class Todo(models.Model):
title = models.CharField(max_length=60)
done = models.BooleanField(default=False)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Todo)
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
fields = ["title", "done"]
def as_dict(t):
return {"id": t.pk, "title": t.title, "done": t.done}
@csrf_exempt
@require_http_methods(["GET", "POST"])
def todo_collection(request):
if request.method == "GET":
return JsonResponse([as_dict(t) for t in Todo.objects.order_by("id")], safe=False)
try:
data = json.loads(request.body)
except json.JSONDecodeError:
return JsonResponse({"error": "invalid JSON"}, status=400)
form = TodoForm(data)
if not form.is_valid():
return JsonResponse({"errors": form.errors}, status=400)
return JsonResponse(as_dict(form.save()), status=201)
@csrf_exempt
@require_http_methods(["PATCH", "DELETE"])
def todo_item(request, pk):
todo = get_object_or_404(Todo, pk=pk)
if request.method == "DELETE":
todo.delete()
return JsonResponse({}, status=204)
form = TodoForm({**as_dict(todo), **json.loads(request.body)}, instance=todo)
if not form.is_valid():
return JsonResponse({"errors": form.errors}, status=400)
return JsonResponse(as_dict(form.save()))
urls.urlpatterns = [path("api/todos/", todo_collection), path("api/todos/<int:pk>/", todo_item)]
c = Client()
r = c.post("/api/todos/", {"title": "Write docs"}, content_type="application/json")
print(r.status_code, r.json())
c.post("/api/todos/", {"title": "Ship v1"}, content_type="application/json")
r = c.post("/api/todos/", {"title": ""}, content_type="application/json")
print(r.status_code, r.json())
r = c.post("/api/todos/", "{oops", content_type="application/json")
print(r.status_code, r.json())
r = c.patch("/api/todos/1/", {"done": True}, content_type="application/json")
print(r.status_code, r.json())
print(c.delete("/api/todos/2/").status_code)
print(c.get("/api/todos/").json())201 {'id': 1, 'title': 'Write docs', 'done': False}
400 {'errors': {'title': ['This field is required.']}}
400 {'error': 'invalid JSON'}
200 {'id': 1, 'title': 'Write docs', 'done': True}
204
[{'id': 1, 'title': 'Write docs', 'done': True}]
With content_type="application/json", the test client encodes a dict argument as a JSON body.
REST conventions in a nutshell
| Method & URL | Action | Success status |
|---|---|---|
GET /api/todos/ |
list | 200 |
POST /api/todos/ |
create | 201 Created |
GET /api/todos/1/ |
retrieve | 200 |
PUT / PATCH /api/todos/1/ |
replace / partially update | 200 |
DELETE /api/todos/1/ |
delete | 204 No Content |
| invalid input | — | 400 Bad Request |
| missing object | — | 404 Not Found |
Tip: Browsers block JavaScript from calling an API on another domain unless the server sends CORS headers. The django-cors-headers package adds them with a middleware and a list of allowed origins.
Test yourself
Why does JsonResponse([1, 2, 3]) raise an error?
- Lists aren't valid JSON
- Non-dict data requires
safe=False - Numbers must be strings
- JsonResponse only accepts models
Which status code fits a successful POST that created a resource?
- 200
- 201
- 204
- 302
Where do you find the raw JSON sent by an API client?
- request.POST
- request.GET
- request.body
- request.json