agyanadda@gmail.com

Building a REST API with Express

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 19 of 30

A REST API exposes data through URLs and HTTP methods, returning JSON.

REST routes for a resource

Method URL Action Success code
GET /api/books list 200
GET /api/books/:id get one 200
POST /api/books create 201
PUT/PATCH /api/books/:id update 200
DELETE /api/books/:id delete 204

Errors: 400 bad input, 401 not logged in, 403 not allowed, 404 not found, 500 server error.

Structure

  • routes/ — URLs
  • controllers/ — request handling
  • models/ or services/ — data access

Validate input

Never trust req.body. Check required fields and types — by hand or with a library such as zod or express-validator.

Extras

  • cors() so frontends on other domains can call the API
  • Pagination: ?page=2&limit=10
  • Consistent error format: { "error": "message" }

Test with Postman, Thunder Client (VS Code) or curl.

Example

Example — Books CRUD API (in-memory) JavaScript
import express from 'express';
import cors from 'cors';

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

let books = [{ id: 1, title: 'Atomic Habits', price: 499 }];
let nextId = 2;

function validate(body) {
  if (!body.title || typeof body.title !== 'string') return 'title is required';
  if (typeof body.price !== 'number' || body.price < 0) return 'price must be a positive number';
}

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

app.get('/api/books/:id', (req, res) => {
  const book = books.find((b) => b.id === Number(req.params.id));
  book ? res.json(book) : res.status(404).json({ error: 'Book not found' });
});

app.post('/api/books', (req, res) => {
  const error = validate(req.body);
  if (error) return res.status(400).json({ error });
  const book = { id: nextId++, title: req.body.title, price: req.body.price };
  books.push(book);
  res.status(201).json(book);
});

app.put('/api/books/:id', (req, res) => {
  const book = books.find((b) => b.id === Number(req.params.id));
  if (!book) return res.status(404).json({ error: 'Book not found' });
  const error = validate(req.body);
  if (error) return res.status(400).json({ error });
  Object.assign(book, { title: req.body.title, price: req.body.price });
  res.json(book);
});

app.delete('/api/books/:id', (req, res) => {
  books = books.filter((b) => b.id !== Number(req.params.id));
  res.status(204).end();
});

app.listen(3000);

curl -X POST localhost:3000/api/books -H "Content-Type: application/json" -d '{"title":"Deep Work","price":399}' returns 201 with the new book. Sending no title returns 400 {"error":"title is required"}.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which status code is used after successfully creating a resource?

Exercise 2 True / False

You should validate req.body before saving it.

Exercise 3 Fill in the Blank

Allow frontends on other domains to call your API with the ___ middleware.

Frequently Asked Questions

PUT replaces the whole resource, so the client sends every field. PATCH changes only the fields sent. Many APIs accept PATCH for partial updates, which is more convenient for forms.