Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

A REST API in JSON

By the end of this chapter, you'll be able to

  • Organise an API around resources and their addresses
  • Map the CRUD operations to HTTP methods
  • Write the handler functions of an in-memory resource
  • Return the right status code for each case

Resources and methods

A REST API (REpresentational State Transfer) organises data into resources: books, students, registrations. Each resource has an address, and HTTP methods say what to do with it. The four basic operations form CRUD (Create, Read, Update, Delete):

OperationRequestResponse on success
listGET /api/books200 + array of books
read oneGET /api/books/4200 + the book
createPOST /api/books + JSON body201 + the created book, with its id
updatePATCH /api/books/4 + JSON body200 + the updated book
deleteDELETE /api/books/4204, no body

Resource names are plural nouns, not verbs: you write POST /api/books, not POST /api/createBook. The method carries the action.

The book is removed. Reading /api/books/3 again would return 404.

Step 4 of 4
Text description of the animation
  1. The client sends the title and author; the server assigns identifier 3 and replies 201 Created.
  2. The client reads the book through its address, built with the identifier.
  3. The client sends only the field that changes: the book is marked as lent.
  4. The book is removed. Reading /api/books/3 again would return 404.

Handler functions

The data is kept in memory here, in an array. In a real application it would be in a database, but the structure of the functions stays the same. Each function receives the URL parameters and the already decoded body, and returns { status, body }:

const books = [
  { id: 1, title: "Ambiguous Adventure", author: "Cheikh Hamidou Kane", lent: false },
  { id: 2, title: "The Suns of Independence", author: "Ahmadou Kourouma", lent: true },
];
let nextId = 3;

const notFound = { status: 404, body: { error: "unknown book" } };
const find = (id) => books.find((b) => b.id === Number(id));

function list() {
  return { status: 200, body: books };
}
function read({ id }) {
  return find(id) ? { status: 200, body: find(id) } : notFound;
}
function create(_, data) {
  const book = { id: nextId++, title: data.title, author: data.author, lent: false };
  books.push(book);
  return { status: 201, body: book };
}
function update({ id }, data) {
  const book = find(id);
  if (!book) return notFound;
  if ("lent" in data) book.lent = data.lent;
  if ("title" in data) book.title = data.title;
  return { status: 200, body: book };
}
function remove({ id }) {
  const index = books.findIndex((b) => b.id === Number(id));
  if (index === -1) return notFound;
  books.splice(index, 1);
  return { status: 204, body: null };
}

console.log(create({}, { title: "So Long a Letter", author: "Mariama Bâ" }).status);
console.log(update({ id: "3" }, { lent: true }).body);
console.log(remove({ id: "1" }).status, read({ id: "1" }).status);
console.log(list().body.map((b) => b.id));
201
{"id":3,"title":"So Long a Letter","author":"Mariama Bâ","lent":true}
204 404
[2,3]

Note that update changes only the fields present in the body: that is what PATCH means. A PUT would replace the whole book.

Reading query parameters

To filter a list, use the query string, the part of the URL after the ?: GET /api/books?lent=false. It is made of name=value pairs separated by &:

function readQuery(url) {
  const [, query = ""] = url.split("?");
  const params = {};
  for (const pair of query.split("&").filter(Boolean)) {
    const [name, value = ""] = pair.split("=");
    params[decodeURIComponent(name)] = decodeURIComponent(value);
  }
  return params;
}

console.log(readQuery("/api/books?lent=false&author=Mariama%20B%C3%A2"));
console.log(readQuery("/api/books"));
{"lent":"false","author":"Mariama Bâ"}
{}

decodeURIComponent turns %20 into a space and %C3%A2 into â: in a URL, special characters are encoded. With Node.js, the URL class does this work: new URL(req.url, "http://localhost").searchParams.get("lent").

Mini-lab: filtering the listJavaScript

Output

Click “Run” to execute your code.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the students resource

Write the list, create and remove functions for a students resource (name and class). list accepts a class query parameter that filters the list. Check with three creations, a filter and a deletion.

Hint 1
Keep a nextId counter outside the functions and increment it on each creation.
Hint 2
remove returns 204 and a null body if the student exists, 404 otherwise.
Show the solution and common mistakes
const students = [];
let nextId = 1;

function list(query) {
  const result = query.class ? students.filter((s) => s.class === query.class) : students;
  return { status: 200, body: result };
}
function create(data) {
  const student = { id: nextId++, name: data.name, class: data.class };
  students.push(student);
  return { status: 201, body: student };
}
function remove(id) {
  const index = students.findIndex((s) => s.id === Number(id));
  if (index === -1) return { status: 404, body: { error: "unknown student" } };
  students.splice(index, 1);
  return { status: 204, body: null };
}

create({ name: "Awa", class: "Final year" });
create({ name: "Kofi", class: "Year 11" });
create({ name: "Lina", class: "Final year" });
console.log(list({ class: "Final year" }).body.map((s) => s.name));
console.log(remove("2").status, remove("2").status);
console.log(list({}).body.length);
["Awa","Lina"]
204 404
2

The second deletion of the same student returns 404: it no longer exists.

Common mistakes:

  • Using filter to delete and reassigning an array declared with const: splice modifies the existing array, without changing the variable.
  • Computing the new identifier with students.length + 1: after a deletion, two students could get the same identifier.

Summary

  1. 1A REST API organises data into resources, named with plural nouns.
  2. 2Methods carry the action: GET reads, POST creates, PATCH partly modifies, DELETE deletes.
  3. 3Each operation has its success code: 200, 201 for a creation, 204 without a body.
  4. 4The query string, after the ?, is used to filter; its values are encoded and always text.
  5. 5Handler functions stay the same whether data is in memory or in a database.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.