A Page That Calls the API
Part of the JSON APIs section of Coddy's Django journey. Lesson 12 of 19.
Your API has a caller inside the site: JavaScript on the home page. The page loads once, then its script asks the API for data and fills the page without a reload. The script, tasks/static/tasks/app.js, is given; your part is the page it needs.
fetch("/api/tasks/") sends a GET from the visitor's browser, and response.json() reads the answer. document.getElementById("task-list") finds the element whose id is task-list, so the page must have one. A script runs as soon as the browser reads its tag, so the tag goes after the elements it uses, at the end of the body. Load it the way you load a stylesheet:
{% load static %}
<link rel="stylesheet" href="{% static 'shop/style.css' %}">The checks cannot run JavaScript, so they test the page and the JSON; the preview runs the script for real.
Challenge
MediumRead tasks/static/tasks/app.js, then in tasks/templates/tasks/home.html:
- Add the list the script fills, with the id it looks up.
- Load
tasks/app.jsthrough{% static %}, placed so the list exists when it runs.
Press Run: the three tasks appear on the home page.
Try it yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task tracker</title>
</head>
<body>
<h1>Task tracker</h1>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in JSON APIs
Practice on your own: Django playground