Loading

T9 APIs · Lesson 1

HTTP and REST

An API is a door that one program opens for others. REST is the set of habits that makes such doors alike: every thing has an address, every request uses one of a few verbs, every answer carries a status code, and no request depends on the one before. Learn them by building and calling a small API of gauges.

  • say what an API is, and how a web API differs from a website
  • name resources with REST addresses: collections, items and queries
  • choose the method for each job, and say which methods are safe and which are idempotent
  • answer with the right status code: 200, 201 with Location, 204, 400, 404, 405 and 409
  • say what stateless means, and why each request carries all it needs
  • design a small API's endpoints, and test them with fetch
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-09); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-09)Play this lesson's games

The back cover

A courier office runs on rules that every courier keeps. Every parcel has an address, every slip says what to do with it, and every reply is stamped with a number that says how it went. The rules make every office work alike.

These pages show such rules for web APIs, the doors that programs open for other programs. They show REST's habits: names for every resource, a few methods for every action, status codes for every answer, and requests that stand alone. They end with designing an API that can change without breaking its clients.

Before you start

The story: A yard of lost parcels

The Couriers' Yard carries questions and parcels between every hall of the city. This morning half of them have come back marked with a question mark.

Each hall writes its requests its own way. The Engine Hall asks for "gauge boiler send", the Clock Tower for "boiler gauge, please", and the Archive pins up a note that says only "GAUGE?". The couriers cannot tell what anyone wants.

Yardmaster Dalia Waybill holds up a parcel with no label and drops it in the returns bin. "A yard runs on rules that every hall shares," she says. "Say what you want done, to which thing, and label every parcel. Learn the rules of the road."

The Node.js track ended with a server that answered fetch. That server was already an API: a door that one program opens for other programs. Most of the internet works through such doors. A weather app asks a weather API for today's forecast, and a shop's page asks the shop's API for the prices.

This track is about building those doors well. This first lesson is about REST, the set of shared habits that make one API look like another, so that a programmer who knows one can use them all.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
A server and its client.http.createServer(listener)Every block is one.
Methods.GET, POSTFive of them, each with a job.
Status codes.200, 404The answer's first word.
Headers.Content-Type: application/jsonLocation joins them.
The path and the query./gauges?unit=CHow a resource is named.
fetch.fetch(url, { method: "POST" })The client in every block.
JSON.JSON.stringify(data)What an API's answers hold.
Reading a body.for await (const c of req)Data sent to the API.
Maps.new Map([["boiler", 95]])The API's store.
Modules.require("./api")The API in a file of its own.

By the end of this lesson you will be able to:

  • say what an API is, and how a web API differs from a website;
  • name resources with REST addresses: collections, items and queries;
  • choose the method for each job, and say which methods are safe and which are idempotent;
  • answer with the right status code: 200, 201 with Location, 204, 400, 404, 405 and 409;
  • say what stateless means, and why each request carries all it needs;
  • design a small API's endpoints, and test them with fetch.

How to follow this lesson

As in the Node.js track, every block is a server and its own client: it listens, asks itself with fetch, prints what it learnt, and closes. Many blocks use the same small API of gauges, kept in a file called api.js and shown above the program, so that each block's own file holds only the client's questions.

In one line

This lesson is about APIs and REST: resources and their addresses, methods, status codes, stateless requests, and designing endpoints.

APIs: programs that answer programs

At a glance

A website answers people with pages. A web API answers programs with data, usually JSON, which a program can use at once. The same server can do both.

Each pair of a method and an address that an API answers is called an endpoint, such as GET /api/gauges. A weather app, a shop's price list and a phone's map all fetch data from endpoints like these. Together, an API's endpoints are a promise: other programs are built on them, and they keep working only while the API keeps its word.

Take a guess: Does India have web APIs of its own for identity and payments?

A website answers people. Its server sends pages of HTML, which a browser draws for a person to read. A web API answers programs. Its server sends data, usually JSON, which a program can use at once.

Here is one server that does both: a page for people at /page, and the same numbers as data for programs at /api/gauges:

app.js

const http = require("http");
const gauges = { boiler: 95, pump: 40 };
const server = http.createServer((req, res) => {
  if (req.url === "/page") {
    res.setHeader("Content-Type", "text/html");
    res.end("<h1>Gauges</h1><p>boiler: 95</p><p>pump: 40</p>");
  } else {
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify(gauges));
  }
});
server.listen(3000, async () => {
  const page = await (await fetch("http://localhost:3000/page")).text();
  console.log(page);
  const data = await (await fetch("http://localhost:3000/api/gauges")).json();
  console.log(data, "total:", data.boiler + data.pump);
  server.close();
});

Terminal: node app.js

<h1>Gauges</h1><p>boiler: 95</p><p>pump: 40</p>
{ boiler: 95, pump: 40 } total: 135

The page is meant to be looked at: to get the numbers out of it, a program would have to pick them out of the tags. The JSON is meant to be used: after r.json(), the numbers are numbers, and adding them takes one line.

Who uses an API

Web pages use APIs, through fetch, to load data without loading a new page. Phone apps use them to talk to their servers. Servers use them to talk to each other, such as a shop's server asking a payment company's API to take a payment.

Endpoints, and the API's promise

Each pair of a method and an address that an API answers is an endpoint, such as GET /api/gauges. Others build their programs on those endpoints, so an API is a promise: these addresses, these methods, these bodies, these status codes.

Changing them breaks every program that relied on them. That is why APIs are designed with care, and why they follow shared habits, which is what the rest of this lesson is about.

A websiteA web API
answerspeople, through a browserprograms
sendspages: HTML, pictures, stylesdata: usually JSON
is readby eyeby code, such as r.json()
is changedwhenever the design changeswith care: programs depend on it

Worked example 1

A phone app shows the hottest gauge in the hall. It asks the hall's API for every gauge, and works out the hottest itself.

What we have: an API whose answer is the JSON object of every gauge and its reading

What we need: the name and reading of the hottest gauge

The plan: fetch the gauges, turn the JSON into an object, sort its entries by reading, and take the first

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ boiler: 95, pump: 40, press: 70 }));
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges");
  const gauges = await r.json();
  const [name, value] = Object.entries(gauges).sort((a, b) => b[1] - a[1])[0];
  console.log(`hottest: ${name} at ${value}`);
  server.close();
});

Terminal: node app.js

hottest: boiler at 95
  1. r.json() gives an object, so Object.entries turns it into pairs of a name and a number.
  2. The sort puts the largest reading first: b[1] - a[1] orders from high to low.
  3. Destructuring takes the name and value of the first pair at once.

The app shows hottest: boiler at 95.

Check: Of 95, 40 and 70, the largest is 95, the boiler's.

A path that fails: asking for the hall's HTML page and cutting the numbers out of its tags. It works until the day someone changes the page's design, and then the app breaks.

When you are stuck: API, endpoint and server blur together

The server is the program that runs. The API is what it offers to other programs. An endpoint is one of its doors: one method and one address.

If a person reads it, it is a page. If a program reads it, it is an API's answer.

Look at the Content-Type: text/html is a page, application/json is data.

Your turn

What does a web API usually send back?Tap to reveal
  1. Programs read it, not people.

Data, usually as JSON.

Name the endpoint that a program uses with fetch("http://localhost:3000/api/gauges").Tap to reveal
  1. fetch uses GET unless told otherwise.

GET /api/gauges.

node -p 'Object.entries({ boiler: 95, pump: 40 }).length'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2
  1. Object.entries gives one pair for each property.
  2. There are two properties.

It prints 2.

Did you know?

India's own stack of APIs

Some APIs serve a whole country. India Stack, in its own words, is a set of open APIs and digital public goods for identity, data and payments at population scale. Wikipedia lists what it covers: identity checks with Aadhaar, payments with UPI and document storage with DigiLocker. It also reports a Financial Times article of 2023 that questioned how open those APIs are.

Why it fits here: It answers this topic's question: India Stack is a set of APIs for identity, data and payments, under Aadhaar, UPI and DigiLocker.

Sources: India Stack; Wikipedia: India Stack

A promise that Linux keeps

Linux treats its interface to programs as a promise. The kernel's own documentation states a no regressions rule: if an application ran fine with one kernel, a newer kernel must not make it work worse, or not at all. A developer who breaks one by accident is expected to fix it quickly. Within that rule, even its APIs may change, as long as no existing application breaks.

Why it fits here: It shows this topic's promise kept at scale: Linux forbids a change that breaks a program which ran before.

Source: The Linux kernel documentation: Reporting regressions

In one line

A web API answers programs with data, usually JSON; each method and address it answers is an endpoint, and together they are a promise that other programs build on.

Resources and their addresses

At a glance

REST is a set of habits for designing web APIs, described by Roy Fielding in 2000. Its first habit is about names.

Everything an API knows about is a resource, and each resource has one address of its own, named with nouns. A collection, such as /gauges, has a plural name. One item of it adds its name or number, as in /gauges/fan. A collection inside an item continues the path, as in /gauges/fan/readings. To filter, sort or page a collection, the client adds a query, such as ?sort=value.

Take a guess: Can a client ask GitHub for as many items on one page as it likes?

REST, short for representational state transfer, is a set of habits for designing web APIs. Roy Fielding described it in 2000, and most web APIs follow it, more or less.

Its first habit is about names. Everything that an API knows about is a resource, such as the gauges, one gauge, or one gauge's readings, and each resource has one address of its own.

Collections and items

A collection holds many things of one kind, and its address is a plural noun: /gauges. One item of it adds its name or number: /gauges/boiler. An item can hold collections of its own: /gauges/boiler/readings.

The address names the thing, never what to do with it. The method, which the next section covers, says what to do.

AddressThe resourceNot like this
/gaugesevery gauge/getGauges, /gauge-list
/gauges/boilerthe gauge called boiler/gauges?name=boiler for one item
/gauges/boiler/readingsthe boiler's readings/boilerReadings
/gauges?above=60the gauges, filtered by a query/hotGauges

This server takes each address apart, the way an API reads it: the collection, the item's name, a collection inside the item, and the query:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  const [collection, name, sub] = url.pathname.split("/").slice(1);
  const query = Object.fromEntries(url.searchParams);
  res.end(JSON.stringify({ collection, name, sub, query }));
});
server.listen(3000, async () => {
  for (const path of ["/gauges", "/gauges/boiler", "/gauges/boiler/readings?limit=2", "/gauges?above=60"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, "->", await r.text());
  }
  server.close();
});

Terminal: node app.js

/gauges -> {"collection":"gauges","query":{}}
/gauges/boiler -> {"collection":"gauges","name":"boiler","query":{}}
/gauges/boiler/readings?limit=2 -> {"collection":"gauges","name":"boiler","sub":"readings","query":{"limit":"2"}}
/gauges?above=60 -> {"collection":"gauges","query":{"above":"60"}}

JSON.stringify leaves out the parts that are undefined, so each answer shows only what the address held. The query's values are always strings, "2" and "60": an API turns them into numbers itself.

The query: filter, sort and page

The query does not name a new resource. It asks for part of a collection, or for it in some order: ?above=60 to filter, ?sort=value to order, ?limit=2 to take a few at a time.

So one address, /gauges, answers many questions, and the API does not grow a new endpoint for each one.

HabitExampleWhy
plural nouns for collections/gaugesthe address names a kind of thing
names or numbers for items/gauges/boiler, /orders/42one address for each thing
small letters, hyphens between words/gauge-readingsaddresses are easy to read and type
the query for filters/gauges?above=60one collection, many questions

Worked example 2

Let the gauges collection answer a filter: GET /gauges?above=60 gives only the gauges that read more than 60, and without the query, all of them.

What we have: three gauges and their readings

What we need: the whole collection, or the part above the number in the query

The plan: read above from the query, as a number; with no query, use minus infinity, so that every reading passes; filter the entries; answer the rest

app.js

const http = require("http");
const gauges = { boiler: 95, pump: 40, press: 70 };
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  const above = Number(url.searchParams.get("above") ?? -Infinity);
  const chosen = Object.fromEntries(Object.entries(gauges).filter(([, v]) => v > above));
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify(chosen));
});
server.listen(3000, async () => {
  for (const path of ["/gauges", "/gauges?above=60", "/gauges?above=90"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, await r.text());
  }
  server.close();
});

Terminal: node app.js

/gauges {"boiler":95,"pump":40,"press":70}
/gauges?above=60 {"boiler":95,"press":70}
/gauges?above=90 {"boiler":95}
  1. searchParams.get gives null without a query, and ?? puts minus infinity in its place.
  2. Number turns the query's string, "60", into the number 60, so the comparison is between numbers.
  3. Object.fromEntries turns the filtered pairs back into an object.

Three answers from one address: all three gauges, then two, then one.

Check: 95 and 70 are above 60; only 95 is above 90.

A path that fails: a new address for each question, such as /hotGauges and /veryHotGauges. The API grows an endpoint for every filter, while one collection with a query answers them all.

When you are stuck: Naming an endpoint

Ask what the thing is, not what you want to do with it: a noun, never a verb.

Many of a kind: a plural, /gauges. One of them: add its name, /gauges/boiler.

Choosing some of a collection: a query, not a new address.

Your turn

Which is the REST address for the readings of the gauge called pump?Tap to reveal
  1. An item can hold a collection of its own.

/gauges/pump/readings.

Why is /deleteGauge a poor address?Tap to reveal
  1. What does the method say?

It puts a verb in the address; the method should say what to do.

node -p 'new URL("/gauges?limit=2", "http://h").searchParams.get("limit") + 1'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
21
  1. A query's value is a string.
  2. A string plus a number joins them.

It prints 21, not 3: the API must turn the query into a number first.

Did you know?

Pages of at most 100

Big collections come in pages. GitHub's documentation for its REST API says that, for most endpoints, the query parameter per_page can ask for at most 100 results on a page. A bigger number gives no error: GitHub lowers it to the maximum. The link header of each answer gives the addresses of the other pages.

Why it fits here: It answers this topic's question: GitHub pages its collections, at most 100 items at a time, with links to the other pages.

Source: GitHub Docs: Using pagination in the REST API

REST's author helped write HTTP

The man who named REST helped write HTTP itself. Roy Fielding's name stands first among the authors of HTTP/1.1, in RFC 2068 of January 1997 and RFC 2616 of June 1999, and he was an editor of RFC 9110, the HTTP standard of June 2022. His dissertation of 2000 says that since 1994 the REST style had guided the design of the modern Web.

Why it fits here: It adds to this topic's REST: Roy Fielding, who named it in 2000, also wrote the HTTP standards themselves.

Sources: RFC 2068: Hypertext Transfer Protocol, HTTP/1.1; RFC 2616: Hypertext Transfer Protocol, HTTP/1.1; RFC 9110: HTTP Semantics; Roy Fielding: Architectural Styles and the Design of Network-based Software Architectures; Roy Fielding's dissertation, chapter 6: Experience and Evaluation

In one line

In REST, every resource has one address, named by nouns: plural collections, items by name or number, collections inside items, and the query to filter, sort or page.

Methods: what to do with a resource

At a glance

The address names the thing, and the method says what to do with it. REST uses five methods for almost everything.

GET reads a collection or an item. POST adds a new item to a collection. PUT replaces an item, PATCH changes part of one, and DELETE removes it. GET is safe: it changes nothing. GET, PUT and DELETE are also idempotent: doing one twice leaves the same result as doing it once, so a client may repeat them when an answer is lost.

Take a guess: Can a plain HTML form send a DELETE request?

The address names the thing; the method says what to do with it. REST uses five methods for almost everything:

MethodOn a collection, such as /gaugesOn an item, such as /gauges/fan
GETread the whole collectionread the item
POSTadd a new item to itrarely used
PUTrarely usedreplace the item, or make it at that address
PATCHrarely usedchange part of the item
DELETErarely usedremove the item

The small API in api.js, shown above the program, keeps gauges in a Map and follows this table. The program's helper, call, sends one request and prints the method, the path, the status and the body, or (no body) when there is none. Here is the whole life of a gauge called fan:

api.js

const http = require("http");
const gauges = new Map([["boiler", 95], ["pump", 40]]);
function send(res, status, data, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(data));
}
module.exports = http.createServer(async (req, res) => {
  const [, collection, name] = new URL(req.url, "http://localhost").pathname.split("/");
  if (collection !== "gauges") return send(res, 404, { error: "not found" });
  let body = "";
  for await (const chunk of req) body += chunk;
  const data = body ? JSON.parse(body) : {};
  if (!name) {
    if (req.method === "GET") return send(res, 200, Object.fromEntries(gauges));
    if (req.method === "POST") {
      if (gauges.has(data.name)) return send(res, 409, { error: `${data.name} already exists` });
      gauges.set(data.name, data.value);
      return send(res, 201, { name: data.name, value: data.value }, { Location: `/gauges/${data.name}` });
    }
    return send(res, 405, { error: "use GET or POST" });
  }
  if (req.method === "PUT") {
    gauges.set(name, data.value);
    return send(res, 200, { name, value: data.value });
  }
  if (!gauges.has(name)) return send(res, 404, { error: `no gauge called ${name}` });
  if (req.method === "GET") return send(res, 200, { name, value: gauges.get(name) });
  if (req.method === "DELETE") {
    gauges.delete(name);
    res.statusCode = 204;
    return res.end();
  }
  return send(res, 405, { error: "use GET, PUT or DELETE" });
});

app.js

const server = require("./api");
server.listen(3000, async () => {
  const call = async (method, path, data) => {
    const r = await fetch("http://localhost:3000" + path, { method, body: data && JSON.stringify(data) });
    console.log(method, path, r.status, (await r.text()) || "(no body)");
  };
  await call("GET", "/gauges");
  await call("POST", "/gauges", { name: "fan", value: 20 });
  await call("GET", "/gauges/fan");
  await call("PUT", "/gauges/fan", { value: 25 });
  await call("DELETE", "/gauges/fan");
  await call("GET", "/gauges");
  server.close();
});

Terminal: node app.js

GET /gauges 200 {"boiler":95,"pump":40}
POST /gauges 201 {"name":"fan","value":20}
GET /gauges/fan 200 {"name":"fan","value":20}
PUT /gauges/fan 200 {"name":"fan","value":25}
DELETE /gauges/fan 204 (no body)
GET /gauges 200 {"boiler":95,"pump":40}

POST added fan to the collection, and its answer, 201, says that something was created. GET read it back. PUT replaced it with a new reading. DELETE removed it, with 204, which has no body, so the helper printed (no body). The last GET shows the collection as it began.

Safe and idempotent

Two words describe what a method may do to the server. A method is safe when it changes nothing on the server: GET only reads. A method is idempotent when sending it once or many times leaves the server in the same state.

This matters because requests get repeated: a network fails, a user presses twice, a program tries again. A repeated GET, PUT or DELETE does no harm. A repeated POST makes a second item, or an error:

api.js

const http = require("http");
const gauges = new Map([["boiler", 95], ["pump", 40]]);
function send(res, status, data, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(data));
}
module.exports = http.createServer(async (req, res) => {
  const [, collection, name] = new URL(req.url, "http://localhost").pathname.split("/");
  if (collection !== "gauges") return send(res, 404, { error: "not found" });
  let body = "";
  for await (const chunk of req) body += chunk;
  const data = body ? JSON.parse(body) : {};
  if (!name) {
    if (req.method === "GET") return send(res, 200, Object.fromEntries(gauges));
    if (req.method === "POST") {
      if (gauges.has(data.name)) return send(res, 409, { error: `${data.name} already exists` });
      gauges.set(data.name, data.value);
      return send(res, 201, { name: data.name, value: data.value }, { Location: `/gauges/${data.name}` });
    }
    return send(res, 405, { error: "use GET or POST" });
  }
  if (req.method === "PUT") {
    gauges.set(name, data.value);
    return send(res, 200, { name, value: data.value });
  }
  if (!gauges.has(name)) return send(res, 404, { error: `no gauge called ${name}` });
  if (req.method === "GET") return send(res, 200, { name, value: gauges.get(name) });
  if (req.method === "DELETE") {
    gauges.delete(name);
    res.statusCode = 204;
    return res.end();
  }
  return send(res, 405, { error: "use GET, PUT or DELETE" });
});

app.js

const server = require("./api");
server.listen(3000, async () => {
  const call = async (method, path, data) => {
    const r = await fetch("http://localhost:3000" + path, { method, body: data && JSON.stringify(data) });
    console.log(method, path, r.status, (await r.text()) || "(no body)");
  };
  await call("POST", "/gauges", { name: "fan", value: 20 });
  await call("POST", "/gauges", { name: "fan", value: 20 });
  await call("PUT", "/gauges/fan", { value: 25 });
  await call("PUT", "/gauges/fan", { value: 25 });
  await call("DELETE", "/gauges/fan");
  await call("DELETE", "/gauges/fan");
  server.close();
});

Terminal: node app.js

POST /gauges 201 {"name":"fan","value":20}
POST /gauges 409 {"error":"fan already exists"}
PUT /gauges/fan 200 {"name":"fan","value":25}
PUT /gauges/fan 200 {"name":"fan","value":25}
DELETE /gauges/fan 204 (no body)
DELETE /gauges/fan 404 {"error":"no gauge called fan"}

The second POST was refused with 409, as fan existed already. The two PUTs left the same reading, 25. The second DELETE found nothing to remove and said 404, but the state after it is the same as after the first: no fan. Idempotent means the same state, not the same answer.

MethodSafeIdempotentSo a repeat is
GETyesyesharmless
POSTnonoa second item, or an error
PUTnoyesharmless: the same item again
PATCHnonot alwaysharmless only if the change sets values
DELETEnoyesharmless: still removed

Worked example 3

The pump's reading must become 45, and the network may send the request twice. Choose the method, and check that a repeat does no harm.

What we have: the API in api.js, where the pump reads 40

What we need: the pump at 45, whether the request arrives once or twice

The plan: PUT the new reading to the pump's own address, twice; then GET the collection to see the state

api.js

const http = require("http");
const gauges = new Map([["boiler", 95], ["pump", 40]]);
function send(res, status, data, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(data));
}
module.exports = http.createServer(async (req, res) => {
  const [, collection, name] = new URL(req.url, "http://localhost").pathname.split("/");
  if (collection !== "gauges") return send(res, 404, { error: "not found" });
  let body = "";
  for await (const chunk of req) body += chunk;
  const data = body ? JSON.parse(body) : {};
  if (!name) {
    if (req.method === "GET") return send(res, 200, Object.fromEntries(gauges));
    if (req.method === "POST") {
      if (gauges.has(data.name)) return send(res, 409, { error: `${data.name} already exists` });
      gauges.set(data.name, data.value);
      return send(res, 201, { name: data.name, value: data.value }, { Location: `/gauges/${data.name}` });
    }
    return send(res, 405, { error: "use GET or POST" });
  }
  if (req.method === "PUT") {
    gauges.set(name, data.value);
    return send(res, 200, { name, value: data.value });
  }
  if (!gauges.has(name)) return send(res, 404, { error: `no gauge called ${name}` });
  if (req.method === "GET") return send(res, 200, { name, value: gauges.get(name) });
  if (req.method === "DELETE") {
    gauges.delete(name);
    res.statusCode = 204;
    return res.end();
  }
  return send(res, 405, { error: "use GET, PUT or DELETE" });
});

app.js

const server = require("./api");
server.listen(3000, async () => {
  const call = async (method, path, data) => {
    const r = await fetch("http://localhost:3000" + path, { method, body: data && JSON.stringify(data) });
    console.log(method, path, r.status, (await r.text()) || "(no body)");
  };
  await call("PUT", "/gauges/pump", { value: 45 });
  await call("PUT", "/gauges/pump", { value: 45 });
  await call("GET", "/gauges");
  server.close();
});

Terminal: node app.js

PUT /gauges/pump 200 {"name":"pump","value":45}
PUT /gauges/pump 200 {"name":"pump","value":45}
GET /gauges 200 {"boiler":95,"pump":45}
  1. PUT names the item's own address and its whole new state, so sending it again sets the same state again.
  2. Both PUTs answered 200 with the same body.
  3. The collection shows the pump at 45, once, and the boiler unchanged.

PUT /gauges/pump, which is idempotent: the pump reads 45 after one request or two.

Check: The GET at the end shows exactly one change: pump from 40 to 45.

A path that fails: GET /gauges/pump?set=45, a GET that changes data. GET is meant to be safe, so browsers, caches and other programs send GETs freely, and they would change the reading by accident.

When you are stuck: Which method?

Only reading: GET. Making a new item, where the server picks or checks its place: POST to the collection.

Setting an item to a whole new state at its own address: PUT. Changing a few of its fields: PATCH. Removing it: DELETE.

Ask whether a repeat would do harm. If it would, the request should not be a GET, and the client must not resend it blindly.

Your turn

Which method adds a new gauge to the collection /gauges?Tap to reveal
  1. The collection decides where the new item goes.

POST.

Is DELETE idempotent, though a second DELETE answers 404?Tap to reveal
  1. Idempotent is about the state, not the answer.

Yes: after one or two, the item is gone.

node -p '["GET", "PUT", "DELETE", "POST"].filter((m) => m !== "POST").length'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3
  1. Of the four, only POST is not idempotent.
  2. The filter keeps the other three.

It prints 3: GET, PUT and DELETE are idempotent.

Did you know?

Forms know two methods

A plain HTML form cannot send PUT, PATCH or DELETE. The HTML standard gives a form's method attribute three keywords: get, post and dialog, and dialog sends nothing at all, as it closes the dialog box that holds the form. A missing or unknown method means GET. So a page that deletes through a REST API does it with JavaScript, such as fetch.

Why it fits here: It answers this topic's question: an HTML form sends only GET or POST, so PUT, PATCH and DELETE need JavaScript.

Source: HTML Standard: Form submission attributes

PATCH came last

PATCH is the youngest of the five. RFC 5789, by Lisa Dusseault and James Snell, added it to HTTP in March 2010. Its reason, in its own words: applications needed partial modification of a resource, while the existing PUT method only allows a complete replacement of a document. So for changing one field, HTTP had no method of its own before 2010.

Why it fits here: It dates this topic's PATCH: it joined HTTP in 2010, to change part of a resource, while PUT replaces all of it.

Source: RFC 5789: PATCH Method for HTTP

In one line

GET reads, POST adds to a collection, PUT replaces an item, PATCH changes part of one, DELETE removes it; GET is safe, and GET, PUT and DELETE are idempotent, so repeating them does no harm.

Status codes in an API

At a glance

A program reads an answer's status code before anything else. So an API chooses its codes with care.

The code 200 says a read or an update worked, 201 says that something new was made, with its address in the Location header, and 204 says it worked with nothing to send back. The codes 400, 404, 405 and 409 say that the client made a mistake, and each comes with an error body saying what went wrong. The code 500 says that the server itself failed.

Take a guess: Is there a status code that is still waiting for its meaning?

A program reads an answer's status code before anything else, so an API chooses its codes with care. These are the ones that a REST API uses most:

CodeIts messageWhen an API uses it
200OKa read, or an update, that worked; the body holds the result
201Createda POST made a new item; the Location header gives its address
204No Contentit worked, and there is nothing to send back, as after a DELETE
400Bad Requestthe request itself is wrong: a body that is not JSON, a missing field
404Not Foundno resource at that address
405Method Not Allowedthe resource exists, but not with that method
409Conflictthe request clashes with what is there, such as an item that exists already
500Internal Server Errorthe server itself failed

201 and the Location header

When a POST creates an item, the answer 201 Created carries a header called Location with the new item's address. A client can follow it at once:

api.js

const http = require("http");
const gauges = new Map([["boiler", 95], ["pump", 40]]);
function send(res, status, data, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(data));
}
module.exports = http.createServer(async (req, res) => {
  const [, collection, name] = new URL(req.url, "http://localhost").pathname.split("/");
  if (collection !== "gauges") return send(res, 404, { error: "not found" });
  let body = "";
  for await (const chunk of req) body += chunk;
  const data = body ? JSON.parse(body) : {};
  if (!name) {
    if (req.method === "GET") return send(res, 200, Object.fromEntries(gauges));
    if (req.method === "POST") {
      if (gauges.has(data.name)) return send(res, 409, { error: `${data.name} already exists` });
      gauges.set(data.name, data.value);
      return send(res, 201, { name: data.name, value: data.value }, { Location: `/gauges/${data.name}` });
    }
    return send(res, 405, { error: "use GET or POST" });
  }
  if (req.method === "PUT") {
    gauges.set(name, data.value);
    return send(res, 200, { name, value: data.value });
  }
  if (!gauges.has(name)) return send(res, 404, { error: `no gauge called ${name}` });
  if (req.method === "GET") return send(res, 200, { name, value: gauges.get(name) });
  if (req.method === "DELETE") {
    gauges.delete(name);
    res.statusCode = 204;
    return res.end();
  }
  return send(res, 405, { error: "use GET, PUT or DELETE" });
});

app.js

const server = require("./api");
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges", { method: "POST", body: JSON.stringify({ name: "fan", value: 20 }) });
  const where = r.headers.get("location");
  console.log(r.status, r.statusText, where);
  const again = await fetch("http://localhost:3000" + where);
  console.log(again.status, await again.json());
  server.close();
});

Terminal: node app.js

201 Created /gauges/fan
200 { name: 'fan', value: 20 }

Saying exactly what went wrong

An API that answers every failure with the same code leaves its clients guessing. The API in api.js says which mistake was made:

api.js

const http = require("http");
const gauges = new Map([["boiler", 95], ["pump", 40]]);
function send(res, status, data, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(data));
}
module.exports = http.createServer(async (req, res) => {
  const [, collection, name] = new URL(req.url, "http://localhost").pathname.split("/");
  if (collection !== "gauges") return send(res, 404, { error: "not found" });
  let body = "";
  for await (const chunk of req) body += chunk;
  const data = body ? JSON.parse(body) : {};
  if (!name) {
    if (req.method === "GET") return send(res, 200, Object.fromEntries(gauges));
    if (req.method === "POST") {
      if (gauges.has(data.name)) return send(res, 409, { error: `${data.name} already exists` });
      gauges.set(data.name, data.value);
      return send(res, 201, { name: data.name, value: data.value }, { Location: `/gauges/${data.name}` });
    }
    return send(res, 405, { error: "use GET or POST" });
  }
  if (req.method === "PUT") {
    gauges.set(name, data.value);
    return send(res, 200, { name, value: data.value });
  }
  if (!gauges.has(name)) return send(res, 404, { error: `no gauge called ${name}` });
  if (req.method === "GET") return send(res, 200, { name, value: gauges.get(name) });
  if (req.method === "DELETE") {
    gauges.delete(name);
    res.statusCode = 204;
    return res.end();
  }
  return send(res, 405, { error: "use GET, PUT or DELETE" });
});

app.js

const server = require("./api");
server.listen(3000, async () => {
  const call = async (method, path, data) => {
    const r = await fetch("http://localhost:3000" + path, { method, body: data && JSON.stringify(data) });
    console.log(method, path, r.status, (await r.text()) || "(no body)");
  };
  await call("GET", "/gauges/fan");
  await call("PATCH", "/gauges/pump", { value: 41 });
  await call("POST", "/gauges", { name: "boiler", value: 1 });
  await call("GET", "/valves");
  server.close();
});

Terminal: node app.js

GET /gauges/fan 404 {"error":"no gauge called fan"}
PATCH /gauges/pump 405 {"error":"use GET, PUT or DELETE"}
POST /gauges 409 {"error":"boiler already exists"}
GET /valves 404 {"error":"not found"}

No gauge called fan: 404. The pump exists, but this API does not offer PATCH: 405. A boiler exists already, so making another would clash: 409. And /valves is no resource at all: 404. Each error also has a body, in the same shape every time, { error: ... }, which a client can show to a person.

Worked example 4

The API in api.js has a gap: a body that is not JSON makes JSON.parse throw, and the server stops. Make a POST answer 400 instead, both for a body that is not JSON and for one with no name.

What we have: three bodies: fan 20, which is not JSON; {"value":20}, which has no name; and a good one

What we need: 400 with a clear message for the first two, and 201 for the third

The plan: parse inside try, and answer 400 from the catch; check that name is a string; only then answer 201 with Location

app.js

const http = require("http");
const server = http.createServer(async (req, res) => {
  const send = (status, data, headers = {}) => {
    res.writeHead(status, { "Content-Type": "application/json", ...headers });
    res.end(JSON.stringify(data));
  };
  let body = "";
  for await (const chunk of req) body += chunk;
  let data;
  try {
    data = JSON.parse(body);
  } catch {
    return send(400, { error: "the body must be JSON" });
  }
  if (typeof data.name !== "string") return send(400, { error: "name is required" });
  send(201, data, { Location: `/gauges/${data.name}` });
});
server.listen(3000, async () => {
  for (const body of ["fan 20", '{"value":20}', '{"name":"fan","value":20}']) {
    const r = await fetch("http://localhost:3000/gauges", { method: "POST", body });
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

400 {"error":"the body must be JSON"}
400 {"error":"name is required"}
201 {"name":"fan","value":20}
  1. A 4xx code says that the client must change the request; repeating it unchanged will fail again.
  2. return send(...) answers and stops the listener there, so no second answer is attempted.
  3. The good body reaches the end, and only it is stored and answered with 201.

400 for both broken bodies, each with its reason, and 201 for the good one.

Check: Only the third body is JSON with a name, and only it got 201.

A path that fails: answering every failure with 200 and a body such as { ok: false }. Clients, tools and caches read the status first, and would take the failure for a success.

When you are stuck: Which status code?

Did it work? 2xx: 200 with a body, 201 after making something, 204 with nothing to send.

Was the request wrong? 4xx: 400 for a broken request, 404 for a missing resource, 405 for a wrong method, 409 for a clash.

Did the server fail? 500. A client cannot fix that by changing its request.

Your turn

Which header of a 201 answer gives the new item's address?Tap to reveal
  1. It says where the item is.

Location.

A client tries to create a gauge whose name is taken. Which code fits?Tap to reveal
  1. The request clashes with what exists.

409 Conflict.

node -p 'require("http").STATUS_CODES[409]'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Conflict
  1. Node keeps every code's message.
  2. 409 is the code for a clash.

It prints Conflict.

Did you know?

402, reserved since 1997

One code has waited for decades. The first standard for HTTP/1.1, RFC 2068 of January 1997, listed 402 Payment Required and said that it was reserved for future use. RFC 9110, the HTTP standard of June 2022, still says that 402 is reserved for future use. So no standard yet says what a 402 answer means.

Why it fits here: It answers this topic's question: 402 Payment Required has been reserved for future use since 1997, and still is.

Sources: RFC 2068: Hypertext Transfer Protocol, HTTP/1.1; RFC 9110: HTTP Semantics

429, for too many requests

An API can tell a client to slow down. RFC 6585, of April 2012, added the code 429 Too Many Requests. It means that the client has sent too many requests in a given amount of time, which the standard calls rate limiting, and the answer should explain the condition. An API that limits how often each key may ask answers with it.

Why it fits here: It adds to this topic's codes: 429 Too Many Requests, from 2012, tells a client that it is asking too often.

Source: RFC 6585: Additional HTTP Status Codes

In one line

200 for a result, 201 with Location for something made, 204 for nothing to send; 400, 404, 405 and 409 for the client's mistakes, each with an error body; 500 for the server's own failure.

Every request stands alone

At a glance

REST asks for one more habit: every request stands alone. The server keeps no memory of a conversation with a client.

Each request carries everything needed to answer it: the method, the address, the query, the headers and the body. A client that wants the second page says page=2 in its query, and a client with a key sends it in a header, every time. The server still keeps its resources, such as the gauges. What it never keeps is where a client has got to, or what it asked before.

Take a guess: Does sending everything with every request have a cost?

REST asks for one more habit: requests are stateless. The server keeps no memory of a conversation with a client. Each request carries everything needed to answer it: the method, the address, the query, the headers and the body.

The server still keeps its resources, such as the gauges. What it does not keep is where a client has got to, or what it asked before.

A server that remembers, and why it hurts

This server offers two ways to read its readings two at a time. /next remembers how far it has got, in a variable; /readings?page=N is told which page, every time:

app.js

const http = require("http");
const readings = [95, 94, 96, 97, 93];
let cursor = 0;
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  if (url.pathname === "/next") {
    const page = readings.slice(cursor, cursor + 2);
    cursor += 2;
    return res.end(JSON.stringify(page));
  }
  const n = Number(url.searchParams.get("page") ?? 1);
  res.end(JSON.stringify(readings.slice((n - 1) * 2, n * 2)));
});
server.listen(3000, async () => {
  const get = async (path) => console.log(path, await (await fetch("http://localhost:3000" + path)).text());
  await get("/next");
  await get("/next");
  await get("/readings?page=1");
  await get("/readings?page=1");
  server.close();
});

Terminal: node app.js

/next [95,94]
/next [96,97]
/readings?page=1 [95,94]
/readings?page=1 [95,94]

Picture the two /next requests coming from two different clients, each wanting the first page. The second one got the second page, because the server remembered the first client's place.

The stateless way answers each request on its own: whoever asks for page 1, and however often, gets page 1. A request can be repeated safely, and any copy of the server can answer it.

Who is asking: on every request

A stateless API does not remember who logged in. A client that must prove who it is sends a key or a token in a header on every request, and the server checks it every time. Without it, the answer is 401 Unauthorized:

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");
  if (req.headers["x-api-key"] !== "hall-6") {
    res.statusCode = 401;
    return res.end(JSON.stringify({ error: "an API key is required" }));
  }
  res.end(JSON.stringify({ boiler: 95 }));
});
server.listen(3000, async () => {
  for (const headers of [{}, { "X-Api-Key": "hall-6" }, {}]) {
    const r = await fetch("http://localhost:3000/gauges", { headers });
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

401 {"error":"an API key is required"}
200 {"boiler":95}
401 {"error":"an API key is required"}

The third request came from the same program that had just succeeded, but without the key. The server did not remember the second request, so it refused the third. The Auth track later shows real keys and tokens; the habit is the same.

Representations

The R in REST stands for representation. The client never gets the resource itself, only a picture of it in some format, which here is JSON. The same gauge could be sent as JSON to a program, or as HTML to a browser; the Content-Type says which picture this is.

Stateful, avoidedStateless, preferred
the server remembers each client's placethe request says which page: ?page=2
the server remembers who logged inevery request carries its key or token
a repeated request may give a different answera repeated request gives the same answer, if the data has not changed
one server must see all of a client's requestsany copy of the server can answer any request

Worked example 5

Read the readings in pages, the stateless way: GET /readings?page=N&size=M, with a body that also says the total, so that a client knows how many pages there are.

What we have: seven readings

What we need: any page of any size, from a request that names both

The plan: read page and size from the query, with 1 and 3 when missing; slice the readings; answer the page, the size, the total and the items

app.js

const http = require("http");
const readings = [95, 94, 96, 97, 93, 92, 98];
const server = http.createServer((req, res) => {
  const url = new URL(req.url, "http://localhost");
  const page = Number(url.searchParams.get("page") ?? 1);
  const size = Number(url.searchParams.get("size") ?? 3);
  const items = readings.slice((page - 1) * size, page * size);
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ page, size, total: readings.length, items }));
});
server.listen(3000, async () => {
  for (const q of ["?page=1", "?page=3", "?page=2&size=2"]) {
    const r = await fetch("http://localhost:3000/readings" + q);
    console.log(q, await r.text());
  }
  server.close();
});

Terminal: node app.js

?page=1 {"page":1,"size":3,"total":7,"items":[95,94,96]}
?page=3 {"page":3,"size":3,"total":7,"items":[98]}
?page=2&size=2 {"page":2,"size":2,"total":7,"items":[96,97]}
  1. Page n of size s starts at (n - 1) * s and stops before n * s, which is what slice takes.
  2. The last page may be short: page 3 of size 3 holds only the seventh reading.
  3. total lets a client work out the number of pages itself: 7 readings in pages of 3 make 3 pages.

Each request got exactly its page, whoever sent it and however often.

Check: Page 1 holds readings 1 to 3, page 3 holds reading 7, and page 2 of size 2 holds readings 3 and 4: 96 and 97.

A path that fails: a current page kept on the server for each client, as /next did. Two clients, or one client retrying after a failure, move each other's place.

When you are stuck: What may the server remember?

Its resources, yes: the gauges, the readings, the orders.

A client's conversation, no: where it has got to, or that it logged in earlier.

If an answer depends on an earlier request, put that information into the request instead: a query, or a header.

Your turn

What does stateless mean for an API?Tap to reveal
  1. Think of the /next endpoint.

Each request carries all it needs; the server remembers no conversation.

Which status code says that a key or token is missing?Tap to reveal
  1. The client must prove who it is.

401 Unauthorized.

node -p '[95, 94, 96, 97, 93].slice(2, 4)'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[ 96, 97 ]
  1. Page 2 of size 2 starts at index 2.
  2. slice stops before index 4.

It prints [ 96, 97 ].

Did you know?

The price of standing alone

Statelessness has a cost, and REST's author named it. Roy Fielding's dissertation calls the stateless rule a design trade-off: since nothing can be left on the server in a shared context, the same data is sent again with every request, which may decrease network performance. The gain is that a server stores nothing between requests, so it can free its resources quickly.

Why it fits here: It answers this topic's question: stateless requests resend the same data, the price of a server that remembers nothing.

Source: Roy Fielding's dissertation, chapter 5: Representational State Transfer (REST)

A key that works for whoever holds it

The key in a header has a standard form. RFC 6750, of October 2012, defines the bearer token, sent as Authorization: Bearer followed by the token. Any party that holds one can use it, the standard says, without proving anything more, much like cash. So a bearer token must be protected from disclosure, both where it is stored and while it travels.

Why it fits here: It names this topic's key in a header: a bearer token, sent as Authorization: Bearer, which works for whoever holds it.

Source: RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage

In one line

REST requests are stateless: each carries everything needed, such as the page in a query or a key in a header; the server keeps resources, never a client's conversation.

Designing an API

At a glance

Designing an API means deciding its endpoints before writing them. A table is the plainest way to write that down.

Each row of the table is an endpoint: its method and path, what it takes, and every answer it can give, the errors too. The table is a promise, so a test checks every row, one request at a time. When the API must change in a way that would break its clients, the new form gets a new version, such as /v2, and the old one keeps working.

Take a guess: Can an API keep its old version alive after a new one comes out?

Designing an API means deciding its endpoints before writing them: the addresses, the methods, what each one takes, and every answer it can give. A table is the plainest way to write that down. Here is the table of the gauges API in api.js:

EndpointTakesAnswers
GET /gaugesnothing200 and every gauge
POST /gaugesa name and a value201 with Location; 409 if the name is taken
GET /gauges/:namenothing200 and the gauge; 404 if there is none
PUT /gauges/:namea value200 and the gauge, made or replaced
DELETE /gauges/:namenothing204; 404 if there is none
any other method405, with the methods that are allowed
any other address404

Writing :name in a path means any name in that place. Express, from lesson 03 on, reads such paths for you.

A table is a promise: test it

Each row of the table is something that clients will rely on, so each row can be checked by a program. The next example runs the whole table against the API.

Worked example 6

Check that the API keeps every promise of its table: run one request for each row, compare the status with the table's, and count the passes.

What we have: the API in api.js, and its table of endpoints

What we need: a pass for every row, or a FAIL that shows which promise is broken

The plan: list each check as a method, a path, a body and the status wanted; send each in turn; compare; print a total

api.js

const http = require("http");
const gauges = new Map([["boiler", 95], ["pump", 40]]);
function send(res, status, data, headers = {}) {
  res.writeHead(status, { "Content-Type": "application/json", ...headers });
  res.end(JSON.stringify(data));
}
module.exports = http.createServer(async (req, res) => {
  const [, collection, name] = new URL(req.url, "http://localhost").pathname.split("/");
  if (collection !== "gauges") return send(res, 404, { error: "not found" });
  let body = "";
  for await (const chunk of req) body += chunk;
  const data = body ? JSON.parse(body) : {};
  if (!name) {
    if (req.method === "GET") return send(res, 200, Object.fromEntries(gauges));
    if (req.method === "POST") {
      if (gauges.has(data.name)) return send(res, 409, { error: `${data.name} already exists` });
      gauges.set(data.name, data.value);
      return send(res, 201, { name: data.name, value: data.value }, { Location: `/gauges/${data.name}` });
    }
    return send(res, 405, { error: "use GET or POST" });
  }
  if (req.method === "PUT") {
    gauges.set(name, data.value);
    return send(res, 200, { name, value: data.value });
  }
  if (!gauges.has(name)) return send(res, 404, { error: `no gauge called ${name}` });
  if (req.method === "GET") return send(res, 200, { name, value: gauges.get(name) });
  if (req.method === "DELETE") {
    gauges.delete(name);
    res.statusCode = 204;
    return res.end();
  }
  return send(res, 405, { error: "use GET, PUT or DELETE" });
});

app.js

const server = require("./api");
const checks = [
  ["GET", "/gauges", undefined, 200],
  ["POST", "/gauges", { name: "fan", value: 20 }, 201],
  ["POST", "/gauges", { name: "fan", value: 20 }, 409],
  ["GET", "/gauges/fan", undefined, 200],
  ["PUT", "/gauges/fan", { value: 25 }, 200],
  ["DELETE", "/gauges/fan", undefined, 204],
  ["GET", "/gauges/fan", undefined, 404],
  ["PATCH", "/gauges/pump", { value: 1 }, 405],
];
server.listen(3000, async () => {
  let passed = 0;
  for (const [method, path, data, want] of checks) {
    const r = await fetch("http://localhost:3000" + path, { method, body: data && JSON.stringify(data) });
    await r.text();
    const ok = r.status === want;
    if (ok) passed += 1;
    console.log(ok ? "pass" : "FAIL", method, path, r.status);
  }
  console.log(`${passed} of ${checks.length} passed`);
  server.close();
});

Terminal: node app.js

pass GET /gauges 200
pass POST /gauges 201
pass POST /gauges 409
pass GET /gauges/fan 200
pass PUT /gauges/fan 200
pass DELETE /gauges/fan 204
pass GET /gauges/fan 404
pass PATCH /gauges/pump 405
8 of 8 passed
  1. The checks run in order, and later rows rely on earlier ones: fan exists only after the POST, and is gone after the DELETE.
  2. await r.text() reads each body even though the check does not need it, so that every answer is finished before the next request.
  3. A FAIL line would name the broken row at once, with the status that came back instead.

8 of 8 passed: the API keeps every promise of its table.

Check: Each status matches the table: 201 then 409 for the same POST, and 404 for fan once it is deleted.

A path that fails: checking only the happy paths, such as GET and POST that work. The promises that break most often are the error answers, such as 409 and 404, which clients rely on too.

Changing an API without breaking its clients

Sometimes an answer's shape must change, such as a list of objects in place of one object. Programs written for the old shape would break. So the new shape gets a new version, often named in the path, and the old one stays for as long as it is used:

app.js

const http = require("http");
const gauges = { boiler: 95, pump: 40 };
const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");
  if (req.url === "/v1/gauges") return res.end(JSON.stringify(gauges));
  if (req.url === "/v2/gauges") return res.end(JSON.stringify(Object.entries(gauges).map(([name, value]) => ({ name, value }))));
  res.statusCode = 404;
  res.end(JSON.stringify({ error: "not found" }));
});
server.listen(3000, async () => {
  for (const p of ["/v1/gauges", "/v2/gauges"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, await r.text());
  }
  server.close();
});

Terminal: node app.js

/v1/gauges {"boiler":95,"pump":40}
/v2/gauges [{"name":"boiler","value":95},{"name":"pump","value":40}]
Design habitWhy
write the table of endpoints firstevery client and every test reads from it
nouns in paths, methods for actionsevery endpoint looks like every other
one shape for every error bodyclients can show any error the same way
the right status code for every answerprograms decide by the code first
a new version for a change that breaksold clients keep working

When you are stuck: An API that grew messy

Write its table: every endpoint, what it takes, every answer. Gaps and clashes show at once.

Rename verbs in paths into nouns plus methods, and give every error the same body shape.

When a change would break clients, add it as a new version instead.

Your turn

Where do many APIs put their version?Tap to reveal
  1. Look at the last block.

In the path, such as /v1/gauges.

What does :name stand for in GET /gauges/:name?Tap to reveal
  1. It is a place, not a name.

Any gauge's name, in that place of the path.

node -p '["GET /gauges", "POST /gauges", "GET /gauges/:name"].filter((e) => e.startsWith("GET")).length'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2
  1. Two of the three endpoints use GET.
  2. filter keeps them.

It prints 2.

Did you know?

GitHub's versions have dates

GitHub names the versions of its REST API by date. Its documentation says that a client chooses one with the header X-GitHub-Api-Version, and that a request without it gets the version 2022-11-28. When a new version comes out, the one before it is supported for at least 24 more months. Breaking changes come only in a new version.

Why it fits here: It answers this topic's question: GitHub dates its versions and keeps the one before for at least 24 months.

Source: GitHub Docs: API Versions

Hyrum's Law

Every visible habit of an API becomes part of its promise. Hyrum's Law says it this way: with a sufficient number of users of an API, it does not matter what you promise in the contract, as all observable behaviors of your system will be depended on by somebody. Its site calls the result bug-for-bug compatibility.

Why it fits here: It warns this topic's designer: once many clients use an API, even its habits that no table lists cannot change safely.

Source: Hyrum's Law

In one line

Design an API as a table of endpoints: method, path, what each takes and every answer; test every row, the errors too, and give a breaking change a new version.

Where it is used

Almost every app you use talks to an API, and most of those APIs follow REST, more or less. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
web APIspages and apps that load dataa shop's page loading prices with fetch
REST addressesalmost every public APIGitHub's API: /repos/OWNER/REPO/issues
methodsmaking, reading, changing and removing dataa to-do app's API, with GET, POST, PUT and DELETE
status codesevery client's first checka phone app that shows Not found for a 404
stateless requestsservers with many copiesa busy site whose requests go to whichever copy is free
a table of endpointsthe documentation of an APIthe OpenAPI documents of the Swagger step, later in the tree

The Yardmaster's rules of the road are REST. Each address is a resource, each verb on a request slip is a method, the number stamped on a reply is the status code, and the courier who remembers nothing between trips is a stateless request.

Mistakes and debugging

These are the slips that people meet most often when they build and call APIs. Every output below is the real one, from the code shown.

1. A query value used as a number

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  const limit = new URL(req.url, "http://localhost").searchParams.get("limit");
  res.end(`next limit: ${limit + 1}`);
});
server.listen(3000, async () => {
  console.log(await (await fetch("http://localhost:3000/readings?limit=2")).text());
  server.close();
});

Terminal: node app.js

next limit: 21

A query's values are strings, so "2" + 1 joined them. The fix: Number(url.searchParams.get("limit")).

2. An error answered with 200

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ ok: false, error: "no such gauge" }));
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges/fan");
  if (r.ok) console.log("found:", await r.json());
  else console.log("missing");
  server.close();
});

Terminal: node app.js

found: { ok: false, error: 'no such gauge' }

The client trusted the status, as clients do, and took the error for a gauge. The fix: answer 404, and keep the error body.

3. A 201 with no Location

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  res.writeHead(201, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ value: 20 }));
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges", { method: "POST", body: '{"name":"fan","value":20}' });
  console.log(r.status, r.headers.get("location"));
  server.close();
});

Terminal: node app.js

201 null

The client was told that something was made, but not where. The fix: send Location: /gauges/fan with every 201.

4. PATCH in small letters

app.js

const http = require("http");
const server = http.createServer((req, res) => {
  console.log("server saw", req.method);
  res.end();
});
server.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/gauges/pump", { method: "patch" });
  console.log("status", r.status, r.statusText);
  server.close();
});

Terminal: node app.js 2>/dev/null

status 400 Bad Request

fetch writes GET, POST, PUT, DELETE, HEAD and OPTIONS in capitals for you, but sends any other method as it was written. Node's server knows its methods only in capitals, so it refused patch with 400 before the listener ran: server saw never printed. fetch also printed a warning on standard error, hidden here. The fix: method: "PATCH".

The debugging corner: the table and the test

When an API surprises you, write its table of endpoints and run a check for every row, as the design section did, printing the method, the path and the status of each answer. The first FAIL points at the endpoint, and the status says what kind of mistake it is.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

app.js

const http = require("http");
const items = new Map([["boiler", 95]]);
const server = http.createServer((req, res) => {
  const [, kind, name] = new URL(req.url, "http://localhost").pathname.split("/");  // /gauges/boiler
  const send = (status, data) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  };
  if (kind !== "gauges") return send(404, { error: "not found" });                  // no such resource
  if (req.method !== "GET") return send(405, { error: "read only" });               // the wrong method
  if (!name) return send(200, Object.fromEntries(items));                           // the collection
  if (!items.has(name)) return send(404, { error: "not found" });                   // no such item
  send(200, { name, value: items.get(name) });                                      // the item
});
server.listen(3000, async () => {
  for (const [method, path] of [["GET", "/gauges/boiler"], ["GET", "/gauges/fan"], ["DELETE", "/gauges/boiler"]]) {
    const r = await fetch("http://localhost:3000" + path, { method });
    console.log(method, path, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

GET /gauges/boiler 200 {"name":"boiler","value":95}
GET /gauges/fan 404 {"error":"not found"}
DELETE /gauges/boiler 405 {"error":"read only"}
When you seeIt meansDo
400the request is wrong: broken body, missing fieldfix the request, then send it again
401no key or token came with the requestsend it in a header, on every request
404no resource at that addresscheck the path and the name
405the resource exists, not with this methoduse a method the endpoint allows
409the request clashes with what existschoose another name, or PUT to replace
201an item was madefollow its Location header
a verb in a paththe design mixes names and actionsa noun for the path, a method for the action

The story: The rules of the road

You learn the yard's rules. Every thing has one address, a noun, such as the gauges or the gauge called boiler. Every request uses one of a few verbs: fetch, add, replace, change, remove. Every reply carries a stamped number, and every parcel a label. And no courier remembers the last trip: each request carries all it needs.

By evening, the Engine Hall and the Clock Tower are trading readings that neither had to explain. Any hall that keeps the rules can talk to any other.

The Yardmaster stamps your slip. "Tomorrow," she says, "the parcels themselves: what goes inside them."

Reagents gathered: API, REST, resource, endpoint, idempotent, stateless.

Sources