Step 1: Plan the API
In this project you will build a small REST API for a to-do list with Node.js: create, list, read, update and delete to-dos, with validation, error handling, saving to a file and automated tests. You use only Node's built-in modules, so there is nothing to install. The examples show the real output of running the code.
Plan before you code. A REST API maps nouns (URLs) and verbs (HTTP methods) to actions. A to-do has an id, a title and a done flag. The routes:
| Method | URL | What it does | Success status |
|---|---|---|---|
| GET | /todos | list all to-dos | 200 |
| POST | /todos | create one | 201 |
| GET | /todos/:id | read one | 200 |
| PATCH | /todos/:id | change it | 200 |
| DELETE | /todos/:id | remove it | 204 |
const routes = [
{ method: "GET", url: "/todos", does: "list all", status: 200 },
{ method: "POST", url: "/todos", does: "create one", status: 201 },
{ method: "GET", url: "/todos/:id", does: "read one", status: 200 },
{ method: "PATCH", url: "/todos/:id", does: "change it", status: 200 },
{ method: "DELETE", url: "/todos/:id", does: "remove it", status: 204 },
];
for (const r of routes) {
console.log(`${r.method.padEnd(6)} ${r.url.padEnd(11)} ${r.status} ${r.does}`);
}GET /todos 200 list all POST /todos 201 create one GET /todos/:id 200 read one PATCH /todos/:id 200 change it DELETE /todos/:id 204 remove it
Writing the plan down as data like this is a good habit: later you can use the same list to build the router and the tests. Errors use standard statuses too: 400 for bad input, 404 when something does not exist. Returning the right status code is what lets other programs use your API without guessing.
Which HTTP method is normally used to create a new item?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.