🎓 A1Learner
🔍
0 of 50 lessons completed

Capstone: A Task API

A task API lists tasks, adds tasks, and marks tasks done. This capstone joins the GET routes, POST routes, and request bodies from this course.

Add a task

This command adds a task to the API.

curl -X POST http://localhost:3000/tasks -H "Content-Type: application/json" -d '{"text":"Buy milk"}'

Mark task 1 done

This command marks task 1 done.

curl -X POST http://localhost:3000/tasks/1/done

Example

const express = require("express");

const app = express();
const tasks = [];

app.use(express.json());

app.get("/tasks", (req, res) => {
  res.json(tasks);
});

app.post("/tasks", (req, res) => {
  const task = { id: tasks.length + 1, text: req.body.text, done: false };
  tasks.push(task);
  res.status(201).json(task);
});

app.post("/tasks/:id/done", (req, res) => {
  let task = null;
  for (const t of tasks) {
    if (t.id === Number(req.params.id)) {
      task = t;
    }
  }
  task.done = true;
  res.json(task);
});

const server = app.listen(3000, async () => {
  const list1 = await (await fetch("http://localhost:3000/tasks")).json();
  console.log("List:", JSON.stringify(list1));

  const added = await (
    await fetch("http://localhost:3000/tasks", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text: "Buy milk" }),
    })
  ).json();
  console.log("Added:", JSON.stringify(added));

  const done = await (
    await fetch("http://localhost:3000/tasks/1/done", { method: "POST" })
  ).json();
  console.log("Done:", JSON.stringify(done));

  const list2 = await (await fetch("http://localhost:3000/tasks")).json();
  console.log("List:", JSON.stringify(list2));

  server.close();
});

Key points

  • A task API lists tasks, adds tasks, and marks tasks done.
  • One array in memory holds the tasks.
  • Each task has an id, a text, and a done flag.
  • A done flag is a true or false value that names completion.
  • GET /tasks sends the whole list.
  • POST /tasks adds one task with done set to false.
  • POST /tasks/1/done marks task 1 done.

In this example, tasks starts as an empty array. The GET route sends the whole list as JSON. The POST route builds a task from the sent body, with done set to false. The done route finds task 1 and sets its done flag to true. The listen line starts the server and runs the client checks. fetch is a call that asks an address for data. The client lists the tasks, adds one, marks it done, and lists again.

Note

A restart clears the tasks, so this API suits learning.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does POST /tasks/1/done do?