← Back to Django, page 3

django-0057 · Easy fresher

How do you read query strings, form data, JSON bodies and headers from a Django HttpRequest, and how do you return JSON?

request.GET and request.POST are QueryDict objects (use get() and getlist()), request.body holds raw bytes that you decode with json.loads for JSON APIs, request.headers is a case-insensitive mapping, and request.method tells you the verb. JsonResponse serialises a dict to JSON with the right content type, and needs safe=False to return a list.

Full answer

Key attributes of HttpRequest:

  • request.method: "GET", "POST" and so on.
  • request.GET: query string. request.GET.get("page", "1") returns the last value; getlist("tag") returns all values.
  • request.POST: form-encoded body (only for form content types). It is empty for JSON requests.
  • request.body: raw bytes. For JSON, json.loads(request.body) and handle json.JSONDecodeError by returning 400.
  • request.headers["User-Agent"] is case-insensitive and normalises names (Content-Type). request.META holds the raw WSGI environ with keys such as HTTP_USER_AGENT and REMOTE_ADDR.
  • request.FILES for uploads, request.COOKIES, request.user and request.session when middleware is enabled, request.path, request.get_full_path() and request.build_absolute_uri().

Responses:

python
return JsonResponse({"ok": True}, status=201)
return JsonResponse([1, 2, 3], safe=False)   # lists need safe=False

JsonResponse uses DjangoJSONEncoder, which handles datetime, Decimal and UUID. Use HttpResponseBadRequest, Http404 or status= for errors.

Validate input: int(request.GET.get("page")) raises on bad input, which becomes a 500. Parse safely or use a Form. For real APIs, Django REST Framework gives parsing, validation and content negotiation, so use it once endpoints grow.

Restrict methods with @require_http_methods(["GET", "POST"]) or @require_POST.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import json

from django.http import JsonResponse
from django.test import RequestFactory
from django.views.decorators.http import require_http_methods


@require_http_methods(["GET", "POST"])
def echo(request):
    if request.method == "GET":
        return JsonResponse({"page": request.GET.get("page", "1"), "tags": request.GET.getlist("tag"),
                             "agent": request.headers.get("user-agent")})
    if request.content_type == "application/json":
        try:
            data = json.loads(request.body)
        except json.JSONDecodeError:
            return JsonResponse({"error": "invalid JSON"}, status=400)
        return JsonResponse({"json": data}, status=201)
    return JsonResponse({"form": request.POST.dict()})


rf = RequestFactory()
print(json.loads(echo(rf.get("/echo/?page=2&tag=a&tag=b", HTTP_USER_AGENT="demo-client")).content))
print(json.loads(echo(rf.post("/echo/", {"name": "Asha"})).content))
r = echo(rf.post("/echo/", data=json.dumps({"score": 91}), content_type="application/json"))
print(r.status_code, json.loads(r.content))
print(echo(rf.post("/echo/", data="{bad", content_type="application/json")).status_code)
print(echo(rf.delete("/echo/")).status_code)
print(JsonResponse([1, 2], safe=False).content)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'page': '2', 'tags': ['a', 'b'], 'agent': 'demo-client'} {'form': {'name': 'Asha'}} 201 {'json': {'score': 91}} 400 405 b'[1, 2]'

Key points

  • GET and POST are QueryDicts; use get() and getlist()
  • JSON bodies come from request.body, not request.POST
  • request.headers is case-insensitive; META has raw keys
  • JsonResponse needs safe=False for non-dict data
  • Return 400 on bad JSON instead of letting it crash

Common mistakes

  • Reading JSON from request.POST
  • Not catching JSONDecodeError
  • Returning a list from JsonResponse without safe=False
  • Trusting query-string values without validation

Follow-ups

  • How does request.GET differ from request.POST?
  • What would DRF add on top of this?
  • How do you read client IP safely behind a proxy?

Tips

  • Name request.body for JSON
  • Mention 400 for bad JSON
  • Explain QueryDict get vs getlist