JsonResponse
Return JSON from a plain Django view with JsonResponse.
Syntax
return JsonResponse({...})To build a simple API without extra packages, return a JsonResponse. Give it a dictionary and Django serializes it to JSON with the right content type.
Pass safe=False to serialize a list at the top level.
Example
from django.http import JsonResponse
from .models import Post
def post_api(request):
data = list(Post.objects.values("id", "title", "published"))
return JsonResponse(data, safe=False)
def single_api(request, pk):
post = Post.objects.get(pk=pk)
return JsonResponse({"id": post.id, "title": post.title})When to use it
- A developer returns a list of products as JSON from a Django view so a React frontend can populate a page.
- A developer uses JsonResponse with safe=False to return a JSON array instead of a dictionary.
- A team uses JsonResponse to return validation errors as structured JSON from a form submission endpoint.
More examples
Return a JSON dict
Returns a JSON object with a 200 status; JsonResponse sets Content-Type to application/json automatically.
from django.http import JsonResponse
def health_check(request):
return JsonResponse({"status": "ok", "version": "1.0"})Return a JSON list with safe=False
Uses safe=False to serialize a list; values() produces dicts directly from the queryset.
from django.http import JsonResponse
from .models import Product
def product_list(request):
data = list(Product.objects.values("id", "name", "price"))
return JsonResponse(data, safe=False)Return error JSON with status
Returns JSON with custom HTTP status codes to signal errors and successful creation to API clients.
from django.http import JsonResponse
def create_product(request):
if request.method != "POST":
return JsonResponse({"error": "Method not allowed"}, status=405)
# ... process data ...
return JsonResponse({"id": 42, "created": True}, status=201)
Discussion