🎓 A1Learner
🔍
0 of 50 lessons completed

Building a JSON API with Django

A JSON API is a set of addresses that serve data. Each address answers with JSON instead of a page.

Make the view

This line imports json and JsonResponse together. The list below holds the posts.

import json

from django.http import JsonResponse

posts = []

One view for both methods

This view checks the method. A POST adds a post, and a GET lists them.

def post_list(request):
    if request.method == "POST":
        post = json.loads(request.body)
        posts.append(post)
        return JsonResponse(post, status=201)
    return JsonResponse(posts, safe=False)

Ask the API

The test client lists the posts, adds one, and lists again. json.dumps turns the dict into JSON text for the POST. The prints show each answer.

client = Client()
print(client.get("/api/posts/").content.decode())
print(client.post("/api/posts/", data=json.dumps({"title": "Second post"}), content_type="application/json").status_code)
print(client.get("/api/posts/").content.decode())

Example

import json

import django
from django.conf import settings

settings.configure(DEBUG=True, SECRET_KEY="key", ROOT_URLCONF=__name__, ALLOWED_HOSTS=["*"])
django.setup()

from django.http import JsonResponse
from django.urls import path

posts = []

def post_list(request):
    if request.method == "POST":
        post = json.loads(request.body)
        posts.append(post)
        return JsonResponse(post, status=201)
    return JsonResponse(posts, safe=False)

urlpatterns = [path("api/posts/", post_list)]

from django.test import Client

client = Client()
print(client.get("/api/posts/").content.decode())
print(client.post("/api/posts/", data=json.dumps({"title": "Second post"}), content_type="application/json").status_code)
print(client.get("/api/posts/").content.decode())

Key points

  • JsonResponse turns a dict into a JSON answer.
  • Use safe=False to answer with a list.
  • json.loads turns JSON text into a dict.
  • A POST reads the sent JSON from request.body.
  • A new item returns the status 201.

In this example, the posts live in a list. The view checks the method of the request. A POST reads the sent JSON, adds it to the list, and returns it with 201. A GET returns the whole list as JSON. The test client lists the empty posts, adds one, then lists once more. The prints show an empty list, the 201 answer, and the list with one post.

Note

An API speaks JSON, not HTML.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does POST /api/posts/ return after adding a post?