Building REST APIs with Express.js

Express is the most popular way to build Node.js APIs

Express is the de facto framework for HTTP APIs in Node. It is thin, unopinionated, and built around two ideas: routes and middleware. Master those and you can build almost anything.

A Minimal API

import express from 'express';
const app = express();
app.use(express.json());

app.get('/health', (req, res) => res.json({ ok: true }));
app.get('/users/:id', (req, res) => {
  res.json({ id: req.params.id });
});
app.listen(3000);

Middleware: The Core Idea

Middleware are functions that run in order on each request. They can read/modify the request, end the response, or pass control with next():

  • Built-inexpress.json() parses request bodies
  • Third-partycors, helmet, morgan
  • Custom — authentication, logging, validation

Routes + middleware compose into a full API

REST Conventions

Method Path Action
GET /users List users
GET /users/:id Get one user
POST /users Create a user
PUT /users/:id Replace a user
DELETE /users/:id Remove a user

Structuring for Growth

  1. Split routes into routers by resource.
  2. Keep business logic in services, not route handlers.
  3. Centralise error handling in one middleware at the end.

Thin controllers, fat services. Route handlers should orchestrate, not implement.

What to Learn Next

  • Validation with Zod or Joi
  • Authentication with JWT or sessions
  • Error handling middleware patterns

Arivanandhan Chitheshwaran