Lesson 2 of 7 · 14 min · 1 hands-on step

Building a REST API

Design endpoints and write the handler logic behind them.

REST in one idea

A REST API exposes resources (notes, users, orders) at URLs, and uses HTTP methods as the verbs:

Endpoint Does
GET /notes list notes
POST /notes create a note
GET /notes/7 read note 7
PATCH /notes/7 update note 7
DELETE /notes/7 delete note 7

URLs are nouns, methods are verbs. Avoid /getNotes or /deleteNote?id=7.

What a handler looks like on a real server

With Node.js and a framework like Express, a handler is a function that receives the request and sends a response:

app.get("/notes/:id", (req, res) => {
  const note = notes.find((n) => n.id === Number(req.params.id));
  if (!note) return res.status(404).json({ error: "Not found" });
  res.json(note);
});

Frameworks handle the networking. Your job is the logic in the middle, which is exactly what the practice exercise has you write, as a plain function you can test.

JSON in, JSON out

APIs almost always send JSON. A client (a browser, a mobile app, another server) calls your API like this:

const res = await fetch("/notes", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ text: "Buy milk" }),
});
const note = await res.json(); // { id: 1, text: "Buy milk" }

Design tip: return consistent shapes. Errors always look like { error: "…" }, lists are always arrays. Front-end developers (and future you) will thank you.

🧪 Practice

Write handle(method, path, body) for an in-memory notes API. It returns { status, body }:

Request Response
GET /notes 200, array of all notes
POST /notes with { text } 201, the new note { id, text } (ids start at 1)
GET /notes/:id 200, that note, or 404 with { error: "Not found" }
DELETE /notes/:id 204 with body null, or 404
anything else 405 with { error: "Method not allowed" }
JavaScript
const notes = [];
let nextId = 1;

function handle(method, path, body) {
  return { status: 405, body: { error: "Method not allowed" } };
}

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. Which is the best REST URL to get user 42's orders?

  2. Which status should a successful create return?

Create a free account to track your progress.