📖 Notes LESSON 25 OF 32

Express REST API

⏱️ 34 min
🟢 Node.js

A Framework for Routes

Express is the most widely used Node.js web framework — it turns the raw http-module pattern from Lesson 24 into a clean, declarative way to define routes and middleware.

Routes, Middleware, CRUD

🛣️
Route
A pairing of an HTTP method + path to a handler function, e.g. GET /api/courses.
🔗
Middleware
A function that runs between the request and the final handler — logging, auth, parsing JSON.
📮
req / res
The request object (body, params, headers) and response object (status, json).
🔄
CRUD
Create, Read, Update, Delete — mapped to POST, GET, PUT/PATCH, DELETE.
Full CRUD for a Course Resource
JS
const express = require('express');
const app = express();
app.use(express.json()); // middleware: parse JSON bodies

let courses = [{ id: 1, title: 'HTML Basics' }];

app.get('/api/courses', (req, res) => {
  res.json(courses);
});

app.get('/api/courses/:id', (req, res) => {
  const course = courses.find(c => c.id === Number(req.params.id));
  if (!course) return res.status(404).json({ error: 'Not found' });
  res.json(course);
});

app.post('/api/courses', (req, res) => {
  const newCourse = { id: courses.length + 1, ...req.body };
  courses.push(newCourse);
  res.status(201).json(newCourse);
});

app.put('/api/courses/:id', (req, res) => {
  const course = courses.find(c => c.id === Number(req.params.id));
  if (!course) return res.status(404).json({ error: 'Not found' });
  Object.assign(course, req.body);
  res.json(course);
});

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

app.listen(3000);
Status codes matter
201 for a successful create, 204 for a successful delete with no body, 404 when a resource isn't found — the frontend's fetch calls (Lesson 18) rely on these to decide how to react.
🗒 Cheat Sheet 📝 Worksheet