REST APIs with Express

Site Admin · 11 Sep 2026 · 9 views

REST APIs with Express

A REST API exposes resources over HTTP so clients can create, read, update, and delete data. Express maps those operations to routes in a natural way.

The REST conventions

Resources have nouns and verbs map to HTTP methods. A list and its items follow a consistent pattern:

GET    /items      list all
POST   /items      create one
GET    /items/:id  read one
PUT    /items/:id  update one
DELETE /items/:id  remove one

A complete items route

Here a route shows the whole flow with a status code:

let items = [];
let nextId = 1;

app.post('/items', (req, res) => {
  const item = { id: nextId++, ...req.body };
  items.push(item);
  res.status(201).json(item);
});

app.get('/items', (req, res) => res.json(items));

app.get('/items/:id', (req, res) => {
  const item = items.find((i) => i.id === Number(req.params.id));
  if (!item) return res.status(404).json({ message: 'Not found' });
  res.json(item);
});

Status codes matter

201 means created, 200 means success, 204 means deleted, 400 is a bad request, and 404 is missing. Sending the right code is part of the contract your API promises to clients.

Validation

Check input before storing it. A tiny guard keeps bad data out:

if (!req.body.name) {
  return res.status(400).json({ error: 'name is required' });
}

Key Points

  • REST uses nouns for resources and verbs for actions.
  • Each CRUD operation maps to a specific method and path.
  • Use proper status codes in every response.
  • Validate input before accepting it.
  • Data lives in memory here; a database replaces it later.
Share this post:

Comments (0)

Please login or register to comment.