All academies

Real-World Projects

Put it all together: build a REST API from scratch.

30 minLevel 20 of 20

The project: a Tasks REST API

Time to combine everything — Express, modules, env vars, error handling, async code, and testing — into one coherent project: a task manager API. It will support the five classic operations:

  • GET /api/tasks — list all tasks
  • GET /api/tasks/:id — fetch one task
  • POST /api/tasks — create a task (validated)
  • PUT /api/tasks/:id — update a task
  • DELETE /api/tasks/:id — remove a task

The key lesson is not any single line of code — it is the structure: small modules with one job each, wired together explicitly. This is the shape of virtually every production Node service you will encounter.

Folder structure
task-api/
  package.json
  .env                  # PORT, NODE_ENV (gitignored!)
  .env.example
  src/
    server.js           # entry point - starts listening
    app.js              # builds the Express app (no listen!)
    config.js           # reads and validates env vars
    routes/
      tasks.routes.js   # URL patterns -> controller functions
    controllers/
      tasks.controller.js # req/res handling, status codes
    services/
      tasks.service.js  # business logic + data access
    middleware/
      errors.js         # AppError classes + error middleware
    validators/
      task.validator.js # input validation
  test/
    tasks.test.js

Layers: routes → controllers → services

Each request flows through three layers, each ignorant of the others' details:

  • Routes map a method + path to a controller function. Nothing else.
  • Controllers speak HTTP: read req, call a service, choose a status code, send a response. No business logic.
  • Services hold business logic and data access. They know nothing about HTTP — they take plain arguments, return plain values, and throw domain errors when things go wrong.

Why bother? Each layer can be tested alone (services need no HTTP mocking), swapped independently (replace the in-memory store with a real database — controllers don't change), and read quickly (each file answers one kind of question).

src/services/tasks.service.js
// Pure business logic - no req, no res, no HTTP.
const { NotFoundError } = require("../middleware/errors");

let tasks = [{ id: 1, title: "Learn Node", done: true }];
let nextId = 2;

exports.list = async () => tasks;

exports.getById = async (id) => {
  const task = tasks.find((t) => t.id === id);
  if (!task) throw new NotFoundError("Task " + id);
  return task;
};

exports.create = async ({ title }) => {
  const task = { id: nextId++, title, done: false };
  tasks.push(task);
  return task;
};

exports.update = async (id, changes) => {
  const task = await exports.getById(id); // throws if missing
  Object.assign(task, changes);
  return task;
};

exports.remove = async (id) => {
  await exports.getById(id);
  tasks = tasks.filter((t) => t.id !== id);
};

Controllers and routes

Controllers translate between HTTP and the service layer: pull parameters out of req, await the service, pick the right status code (200 read, 201 created, 204 deleted). Every controller is wrapped in a tiny asyncHandler helper that forwards rejected promises to the error middleware — no repetitive try/catch in each function.

The router is then a clean, readable table of endpoints.

Controller + routes
// src/controllers/tasks.controller.js
const service = require("../services/tasks.service");
const { validateTask } = require("../validators/task.validator");

const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

exports.list = asyncHandler(async (req, res) => {
  res.json(await service.list());
});

exports.create = asyncHandler(async (req, res) => {
  const input = validateTask(req.body); // throws ValidationError
  res.status(201).json(await service.create(input));
});

exports.remove = asyncHandler(async (req, res) => {
  await service.remove(Number(req.params.id));
  res.status(204).end();
});

// src/routes/tasks.routes.js
const router = require("express").Router();
const ctrl = require("../controllers/tasks.controller");
router.get("/", ctrl.list);
router.post("/", ctrl.create);
router.delete("/:id", ctrl.remove);
module.exports = router;

Validation and error handling

Never trust input. The validator checks the request body at the boundary and throws a ValidationError (status 400) with a helpful message. Services throw NotFoundError (404) for missing records. Both extend one AppError base class carrying a statusCode — exactly the pattern from the error-handling lesson.

The error middleware is the single place that turns any thrown error into an HTTP response: known AppErrors use their own status and message; anything unexpected is logged and answered with a generic 500 (never leak stack traces to clients).

Validator and error middleware
// src/validators/task.validator.js
const { ValidationError } = require("../middleware/errors");

exports.validateTask = (body) => {
  if (!body || typeof body !== "object")
    throw new ValidationError("Body must be a JSON object");
  if (typeof body.title !== "string" || body.title.trim() === "")
    throw new ValidationError("'title' is required and must be a non-empty string");
  if (body.title.length > 200)
    throw new ValidationError("'title' must be at most 200 characters");
  return { title: body.title.trim() };
};

// src/middleware/errors.js
class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
  }
}
class NotFoundError extends AppError {
  constructor(what) { super(what + " not found", 404); }
}
class ValidationError extends AppError {
  constructor(msg) { super(msg, 400); }
}

function errorMiddleware(err, req, res, next) {
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({ error: err.message });
  }
  console.error("Unexpected error:", err); // log the real cause...
  res.status(500).json({ error: "Internal Server Error" }); // ...hide it from clients
}

module.exports = { AppError, NotFoundError, ValidationError, errorMiddleware };

Wiring it together: app.js and server.js

The final assembly follows one deliberate split: app.js builds the app; server.js starts it. Tests import the app and drive it directly — no port, no network — while production runs server.js.

Order matters in app.js: body parsing first, then routes, then the 404 catch-all, and the error middleware last.

app.js and server.js
// src/app.js
const express = require("express");
const tasksRouter = require("./routes/tasks.routes");
const { errorMiddleware } = require("./middleware/errors");

const app = express();
app.use(express.json());

app.get("/health", (req, res) => res.json({ ok: true }));
app.use("/api/tasks", tasksRouter);

app.use((req, res) => res.status(404).json({ error: "Route not found" }));
app.use(errorMiddleware); // ALWAYS last

module.exports = app;

// src/server.js
const app = require("./app");
const config = require("./config");

app.listen(config.port, () => {
  console.log("Tasks API listening on port " + config.port);
});

Where to go from here

You now hold the complete skeleton of a production Node service. Ways to grow it, roughly in order:

  • Persistence — swap the in-memory array for SQLite or PostgreSQL; only the service layer changes
  • Authentication — JWT middleware protecting write routes
  • Tests — drive app with node:test plus supertest; test the service layer directly
  • Hardening — request logging, rate limiting, CORS, helmet security headers
  • Deployment — Dockerfile, health checks, env-based config, a process manager

Build something real: a bookmarks API, a poll app, a URL shortener. Every project deepens the same muscles — and congratulations on completing all 20 levels of NodeAcademy!

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

In the routes → controllers → services structure, where does business logic belong?