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 asks 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 answer 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
EasyGive the task tracker its first endpoint:
- A view
statsthat answers JSON withtotal, the number of tasks, anddone, the number of done tasks. - The route
"api/stats/", namedstats.
Press Run, then open /api/stats/: it 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