Menu
CoddyTech

What Is an API

Part of the JSON APIs section of Coddy's Django journey. Lesson 1 of 19.

The views you wrote so far return pages for people to read. An API (application programming interface) returns data for programs. A phone app, a script or the JavaScript on a page requests a URL and gets data back instead of HTML.

That data is usually JSON, text that looks like Python dictionaries and lists, with double quotes and true, false and null where Python has True, False and None:

{"title": "Buy milk", "done": false, "due": null}

Django turns a dictionary into a JSON response with JsonResponse:

from django.http import JsonResponse


def hello(request):
    return JsonResponse({"message": "Hi", "ready": True})

It writes the JSON and sets the Content-Type header to application/json. A header is a line of information sent with the response; this one tells the program what kind of data it got.

challenge icon

Challenge

Easy

Give the task tracker its first endpoint, a URL that responds with numbers instead of a page.

  1. In tasks/views.py, import JsonResponse from django.http and add a view stats that responds with JSON: total, the number of tasks, and done, the number of done tasks.
  2. In tasks/urls.py, add the route "api/stats/" named stats.

Press Run: the preview opens /api/stats/ and shows {"total": 3, "done": 1}.

Try it yourself

from django.shortcuts import render

from .models import Task


def home(request):
    return render(request, "tasks/home.html", {"tasks": Task.objects.all()})

All lessons in JSON APIs

Practice on your own: Django playground