Building a REST API with Express

Intermediate · 43 min

Put a small Express 5 API together with JSON parsing, helmet, cors, static files, a routes/service split, and Zod validation of params, query and body.

Before thisExpress routing and middlewareExpress error handling and async routes

PedroTech · 183 min · from 20:38

Building a REST API with Express

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by PedroTechReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A small API has a clear request path: security and parsing middleware, then a router per resource, then a service layer holding the logic, then a central error handler.
  • `express.json({ limit })` parses JSON bodies and rejects oversized ones, `helmet()` sets security headers, and `cors({ origin: [...] })` allows only the browser origins you list.
  • Keep `req` and `res` out of the service layer. Routes translate HTTP into plain function calls, so the logic is testable and reusable.
  • Validate every input boundary with a schema, here Zod 4's `safeParse`. Coercion (`z.coerce.number()`) handles string params and query values, and `z.flattenError` produces a client-friendly 400 body.
  • In Express 5 `req.query` is read-only, so a validation middleware should store parsed query and params elsewhere, such as `res.locals`, and only overwrite `req.body`.

From routes to an API

Routing and middleware and error handling are the parts. An API is how you arrange them. The goal is that every request takes the same predictable path:

  1. Security and parsing middleware (helmet, CORS, JSON body).
  2. A router per resource.
  3. Per route: validate input, call a service, shape the response.
  4. A central error handler.

The app factory

import express from 'express';
import helmet from 'helmet';
import cors from 'cors';

export function createApp() {
  const app = express();
  app.disable('x-powered-by');
  app.use(helmet());
  app.use(cors({ origin: ['https://app.example.com'] }));
  app.use(express.json({ limit: '100kb' }));
  app.use(express.static(new URL('./public', import.meta.url).pathname));
  app.use('/api/todos', router);
  app.use('/api', (req, res) => res.status(404).json({ error: 'Not found' }));
  app.use((err, req, res, next) => {
    if (res.headersSent) return next(err);
    if (err.type === 'entity.parse.failed') return res.status(400).json({ error: 'Invalid JSON' });
    if (err.type === 'entity.too.large') return res.status(413).json({ error: 'Body too large' });
    console.error(err);
    res.status(500).json({ error: 'Internal Server Error' });
  });
  return app;
}

Returning the app from a function instead of calling listen here lets tests mount it without opening a port. What each piece does, checked by running it:

  • helmet() adds headers such as X-Content-Type-Options: nosniff and Strict-Transport-Security. The response had both.
  • cors({ origin: [...] }) sets Access-Control-Allow-Origin only for listed origins: https://app.example.com got its origin echoed back; https://evil.example got no header. CORS is a browser rule, not authentication. The mechanism itself is explained in CORS and content negotiation.
  • express.json({ limit }) parses JSON, and bad JSON triggers an error with type: 'entity.parse.failed', which the handler maps to 400.
  • express.static serves files from public. GET / returned the index.html.

Validate at the boundary

Never trust req.params, req.query or req.body. Describe what valid input looks like once, with a schema:

import { z } from 'zod';

const idParams = z.object({ id: z.coerce.number().int().positive() });
const createBody = z.object({ title: z.string().trim().min(1).max(100) });
const listQuery = z.object({
  done: z.enum(['true', 'false']).transform((v) => v === 'true').optional(),
  limit: z.coerce.number().int().min(1).max(100).default(20),
});

const validate = (schemas) => (req, res, next) => {
  for (const part of ['params', 'query', 'body']) {
    if (!schemas[part]) continue;
    const result = schemas[part].safeParse(req[part]);
    if (!result.success) {
      return res.status(400).json({ error: 'Validation failed', issues: z.flattenError(result.error) });
    }
    if (part === 'body') req.body = result.data;
    else res.locals[part] = result.data; // req.query is read-only in Express 5
  }
  next();
};

URL parts are always strings, so z.coerce.number() converts them. In my run (Zod 4.6), /api/todos/abc returned 400 with {"fieldErrors":{"id":["Invalid input: expected number, received NaN"]}}, and ?limit=999 returned 400 for exceeding the maximum. The parsed limit defaults to 20 when absent. A body of { "title": " write " } was trimmed to write. The schema is both the validator and the documentation of the API’s input.

Routes and services

const todos = new Map();
let nextId = 1;
const todoService = {
  list: ({ done, limit }) => [...todos.values()].filter((t) => done === undefined || t.done === done).slice(0, limit),
  get: (id) => todos.get(id),
  create: (data) => { const t = { id: nextId++, done: false, ...data }; todos.set(t.id, t); return t; },
  remove: (id) => todos.delete(id),
};

const router = express.Router();
router.get('/', validate({ query: listQuery }), (req, res) => res.json(todoService.list(res.locals.query)));
router.post('/', validate({ body: createBody }), (req, res) => {
  const todo = todoService.create(req.body);
  res.status(201).location(`/api/todos/${todo.id}`).json(todo);
});
router.get('/:id', validate({ params: idParams }), (req, res) => {
  const todo = todoService.get(res.locals.params.id);
  if (!todo) return res.status(404).json({ error: 'Not found' });
  res.json(todo);
});
router.delete('/:id', validate({ params: idParams }), (req, res) => {
  if (!todoService.remove(res.locals.params.id)) return res.status(404).json({ error: 'Not found' });
  res.status(204).end();
});

The service knows nothing about HTTP, which is the point. The route chooses status codes (201 with a Location header on create, 204 on delete, 404 on a missing id). Swapping the Map for a database later changes the service only. In a real project each resource gets its own folder with routes, service, and schemas files. The directory layout matters less than keeping HTTP concerns in the routes.

I ran the full set of calls (create, bad create, bad JSON, bad id, get, patch, list with filters, delete twice) and each returned the status shown in the code comments above. The full file is about 100 lines. Persistence is the data group, and supertest is how you would test this app through createApp().

What the video covers

This lesson embeds a 43-minute clip (20:38 to 1:03:38) of PedroTech’s December 2025 “Backend Complete Course”. By its chapter list the clip contains Routes, “PostgreSQL and Prisma” and Controllers. So it shows routes and the controller split in an Express project, but also spends time on Prisma setup, which belongs to the later ORM lesson. The video is marked as sponsored by the creator. The course’s Zod validation chapter (2:11:00) is outside the clip and linked under “go deeper”. Body parsing, helmet, CORS, static files and the Zod 4 middleware above come from this page. I could not read a transcript.

Where this fits

This lesson ties the Express group together. Next: authentication adds protected routes. For input validation as a security topic, see input validation and injection attacks, and for the design of the API’s contract, REST resource modeling.

Check yourself

  1. 01Why is a service layer worth having in a small Express API?

    It holds the logic as plain functions with no `req` or `res`, so you can call it from a route, a job, or a test directly. Routes then only translate HTTP: parse and validate input, call the service, choose a status code.

  2. 02`GET /api/todos/abc` should return 400, not crash. Where does that happen in the example?

    In a validation middleware using `z.object({ id: z.coerce.number().int().positive() })`. `'abc'` coerces to `NaN`, the schema fails, and the middleware answers 400 with the field errors before the handler runs.

  3. 03Why does the validation middleware write the parsed query to `res.locals.query` instead of `req.query`?

    In Express 5 `req.query` is a getter you cannot assign to, so overwriting it throws a `TypeError`. `res.locals` is a free slot that lasts for the request, so the handler reads the parsed, typed values from there.

  4. 04What does `cors({ origin: ['https://app.example.com'] })` do for a request from `https://evil.example`?

    It sends no `Access-Control-Allow-Origin` header, so the browser blocks the page from reading the response. CORS is enforced by browsers; it is not authentication and does not stop other clients, such as `curl`, from calling the API.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark