Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 43 ยท Projects

Project: Todo REST API

Build a complete Todo REST API: CRUD routes, input validation, a central error handler and tests. Real Express code is read-only; a runnable stand-in shows it work.

Time to put the pieces together. In this project you build a Todo API with the five operations every REST service needs (create, list, read, update, delete), validate what clients send, return errors in one consistent shape, and test the result. A todo list is a deliberately boring domain: it lets you focus on the structure you will reuse in real services.

Because Express cannot be installed on this site, the final real Express code is read-only. The runnable examples use the same design on our stand-in framework (it has app.get, req.params, res.json, next and error handlers like Express), with an in-memory Map as the database. The route, validation and error logic is what you would carry over unchanged; only the express() import and the body parser line differ.

What we are building

POST /api/todos Create a todo, answer 201.
GET /api/todos List, optionally filtered by done.
GET /api/todos/:id One todo, or 404.
PATCH and DELETE Change fields, or remove with 204.
1 / 2

Design first

Before code, write the contract. A todo has an id (number), a title (1 to 80 characters), a done flag, and a createdAt timestamp. The status codes follow the conventions from Designing a REST API:

Request Success Failure
POST /api/todos 201 with the new todo and a Location header 400 bad JSON, 422 invalid fields
GET /api/todos 200 with an array
GET /api/todos/:id 200 404
PATCH /api/todos/:id 200 with the updated todo 404, 422
DELETE /api/todos/:id 204 with no body 404

400 means "I could not even read your request" (malformed JSON); 422 means "I read it, but the values are not acceptable". Errors always have the same body, so clients write one error handler.

The real Express version (read-only)

This is the whole service in real Express 5, split the way Controllers and Services recommends, shown as a single file for readability. It cannot run here.

JavaScript
import express from 'express';

class HttpError extends Error {
  constructor(status, message, details) {
    super(message);
    this.status = status;
    this.details = details;
  }
}

export function createApp(store = new Map()) {
  let nextId = 1;
  const app = express();
  app.use(express.json({ limit: '10kb' }));

  const findTodo = (id) => {
    const todo = store.get(Number(id));
    if (!todo) throw new HttpError(404, `Todo ${id} not found`);
    return todo;
  };

  function validate(body, { partial }) {
    const errors = {};
    if (!partial || 'title' in body) {
      if (typeof body.title !== 'string' || body.title.trim() === '') {
        errors.title = 'Title is required';
      } else if (body.title.length > 80) {
        errors.title = 'Title must be at most 80 characters';
      }
    }
    if ('done' in body && typeof body.done !== 'boolean') {
      errors.done = 'done must be true or false';
    }
    if (Object.keys(errors).length > 0) {
      throw new HttpError(422, 'Validation failed', errors);
    }
  }

  app.get('/api/todos', (req, res) => {
    let todos = [...store.values()];
    if (req.query.done !== undefined) {
      todos = todos.filter((t) => String(t.done) === req.query.done);
    }
    res.json(todos);
  });

  app.get('/api/todos/:id', (req, res) => res.json(findTodo(req.params.id)));

  app.post('/api/todos', (req, res) => {
    const body = req.body ?? {};
    validate(body, { partial: false });
    const todo = { id: nextId++, title: body.title.trim(), done: false, createdAt: new Date().toISOString() };
    store.set(todo.id, todo);
    res.status(201).location(`/api/todos/${todo.id}`).json(todo);
  });

  app.patch('/api/todos/:id', (req, res) => {
    const todo = findTodo(req.params.id);
    const body = req.body ?? {};
    validate(body, { partial: true });
    if ('title' in body) todo.title = body.title.trim();
    if ('done' in body) todo.done = body.done;
    res.json(todo);
  });

  app.delete('/api/todos/:id', (req, res) => {
    findTodo(req.params.id);
    store.delete(Number(req.params.id));
    res.status(204).end();
  });

  app.use((req, res) => {
    res.status(404).json({ error: { message: `No route for ${req.method} ${req.path}` } });
  });

  app.use((err, req, res, next) => {
    const status = err.status ?? (err.type === 'entity.parse.failed' ? 400 : 500);
    res.status(status).json({
      error: {
        message: status === 500 ? 'Internal Server Error' : err.message,
        details: err.details,
      },
    });
  });

  return app;
}
JavaScript
// server.js
import { createApp } from './app.js';

createApp().listen(3000, () => console.log('Todo API on http://localhost:3000'));

Points worth noticing:

  • createApp(store) does not call listen. Tests can build an app with their own store without opening port 3000.
  • Handlers throw instead of building error responses. In Express 5, a throw (even in async code) reaches the error handler; in Express 4, synchronous throws do, but async rejections need next(err). See Error Handling.
  • express.json rejects malformed JSON with an error that has type: 'entity.parse.failed', which the handler maps to 400.
  • The 404 middleware comes after all routes but before the error handler.
  • Unexpected errors (500) never leak their message to the client.

The runnable stand-in

The stand-in framework does not ship a body parser, so the example adds a tiny middleware that reads and parses JSON. Everything else is the same code as above. Run it and follow the status codes.

Node.js The Todo API, end to end

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check each line against the table in the design section: 201 with a trimmed title, 422 with field details, 400 for broken JSON, 200 for a partial update, 404 for a missing id, 204 (empty body) for delete, and a JSON 404 for an unknown path.

Testing the API

A service is only finished when its behavior is pinned down by tests. In real projects you use node:test (or Vitest or Jest) with Supertest; see Testing Express Apps. The real shape looks like this (read-only):

JavaScript
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './app.js';

test('creating a todo returns 201 and a Location header', async () => {
  const res = await request(createApp()).post('/api/todos').send({ title: 'Test' });
  assert.equal(res.status, 201);
  assert.equal(res.headers.location, '/api/todos/1');
});

Each test builds a fresh app with a fresh store, so tests never depend on each other. The stand-in version below uses fetch against a real loopback server and a tiny test helper, so the checks run right here. The app is reduced to the parts under test.

Node.js Tests with a fresh store each time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Every test boots its own server and store, so the last test proves that earlier tests left nothing behind. Try breaking the validation in the app and watch the matching test report FAIL with a message.

Ideas to extend it

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does createApp return an app without calling listen?

    Separating the app from the server lets tests build as many fresh apps as they like and is also useful for tools and serverless platforms.
  2. 2. A client sends valid JSON, but the title is an empty string. Which status fits best?

    The request could be parsed, but its values break the rules, which is what 422 expresses. 400 is for unreadable requests such as broken JSON.
  3. 3. What should a successful DELETE respond with in this API?

    204 means success with nothing to return. Deleting a missing todo returns 404 instead.
  4. 4. Why does the error handler hide the message when the status is 500?

    Expected errors (404, 422) have messages written for clients; unexpected ones may leak internals, so clients get a generic text and the details go to the logs.

Summary

  • Write the contract first: routes, status codes and one error shape.
  • Keep handlers short: validate, call the store, respond; throw HttpError for failures.
  • createApp(store) without listen makes injection and testing easy.
  • Use 400 for unreadable input, 422 for invalid values, 404 for missing resources and 204 for empty success.
  • Give every test a fresh app and store so tests stay independent.

Next: Project: Authenticated Notes API.