Back end with Node

Level recap · Back end with Node · Level 2

An HTTP API

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Build a server that answers requests with the right status, headers and JSON.

14 classesLevel exam

Take the level exam
  1. 1Your first server

    http.createServer answers every request.

    The idea

    Ticket CL-401: the shop's new back end starts as one small server. The front-end team wants to see it answer before anything else is built.

    http.createServer(handler) makes a server. Node calls your handler once for every request, with two objects: req, the request (req.method is "GET" or "POST", req.url is the path, like /products?max=50), and res, the response you send back. res.end(text) sends the text and finishes the answer.

    The code

    const http = require("http");
    const server = http.createServer((req, res) => {
      res.end("Copperleaf API: you asked for " + req.method + " " + req.url);
    });
    const port = Number(process.env.PORT ?? 3000);
    server.listen(port, () => console.log("Listening on port " + port));

    What it shows

    PASS Every request gets an answer with its own method and path
  2. 2Routes

    Pick the answer from the method and the path.

    The idea

    Ticket CL-402: monitoring needs GET /health, and the shop front needs GET /products/count. Everything else must say it does not exist.

    A route is a method plus a path. Check both: if (req.method === "GET" && req.url === "/health"). A POST /health is a different route. Set the status before you end: res.statusCode = 404;. 200 (OK) is the default.

    The code

    const http = require("http");
    const fs = require("fs");
    const products = JSON.parse(fs.readFileSync("products.json", "utf8"));
    const server = http.createServer((req, res) => {
      if (req.method === "GET" && req.url === "/health") {
        res.end("ok");
      } else if (req.method === "GET" && req.url === "/products/count") {
        res.end(String(products.length));
      } else {
        res.statusCode = 404;
        res.end("Not found");
      }
    });
    server.listen(3000, () => console.log("Listening on port 3000"));

    What it shows

    PASS GET /health answers ok
  3. 3Answer with JSON

    Status codes, the Content-Type header and JSON.stringify.

    The idea

    Ticket CL-403: the shop front will read the product list from the API. It needs real JSON, and a clear JSON error when something is not there.

    An API answers with JSON: JSON.stringify(data) as the body, and the header Content-Type: application/json, so the other side knows how to read it. res.writeHead(200, { "Content-Type": "application/json" }) sets the status and the headers in one go.

    The code

    const http = require("http");
    const fs = require("fs");
    const products = JSON.parse(fs.readFileSync("products.json", "utf8"));
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    const server = http.createServer((req, res) => {
      if (req.method === "GET" && req.url === "/products") return sendJson(res, 200, products);
      sendJson(res, 404, { error: "Not found" });
    });
    server.listen(3000, () => console.log("Listening on port 3000"));

    What it shows

    PASS GET /products answers the file's products as JSON
  4. 4Read the request body

    A POST sends data; read it and parse it.

    The idea

    Ticket CL-404: before an order is placed, the checkout page asks the API for the total: it POSTs the cart and gets the total back.

    The body of a request arrives in pieces, so you collect them: let body = ""; for await (const chunk of req) body += chunk;. That loop needs an async handler. Then JSON.parse(body) gives you the object.

    The code

    const http = require("http");
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    async function readJson(req) {
      let body = "";
      for await (const chunk of req) body += chunk;
      return JSON.parse(body);
    }
    const server = http.createServer(async (req, res) => {
      if (req.method === "POST" && req.url === "/quote") {
        const cart = await readJson(req);
        const total = cart.items.reduce((sum, it) => sum + it.price * it.qty, 0);
        return sendJson(res, 200, { total: Math.round(total * 100) / 100 });
      }
      sendJson(res, 404, { error: "Not found" });
    });
    …

    What it shows

    PASS POST /quote adds up the cart in the body
  5. 5Query strings

    Read ?max=50&sort=price with URL and searchParams.

    The idea

    Ticket CL-405: the shop front wants to filter products by price and sort them: GET /products?max=50&sort=price.

    The part after ? is the query string. req.url holds the whole thing, so req.url === "/products" fails once there is a query. Parse it: const url = new URL(req.url, "http://localhost");. Then url.pathname is /products and url.searchParams.get("max") is "50", or null when it is not there.

    The code

    const http = require("http");
    const fs = require("fs");
    const products = JSON.parse(fs.readFileSync("products.json", "utf8"));
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    const server = http.createServer((req, res) => {
      const url = new URL(req.url, "http://localhost");
      if (req.method === "GET" && url.pathname === "/products") {
        let list = products.slice();
        const max = url.searchParams.get("max");
        if (max !== null) list = list.filter((p) => p.price <= Number(max));
        if (url.searchParams.get("sort") === "price") list.sort((a, b) => a.price - b.price);
        return sendJson(res, 200, list);
      }
      sendJson(res, 404, { error: "Not found" });
    });
    …

    What it shows

    PASS ?max= keeps only the products at or under that price
  6. 6One item by its id

    Paths like /products/12, with 404 and 400.

    The idea

    Ticket CL-406: the product page loads one product: GET /products/12.

    The id is part of the path. Split it: const parts = url.pathname.split("/") gives ["", "products", "12"]. Or match it: /^\/products\/([^/]+)$/.exec(url.pathname).

    The code

    const http = require("http");
    const fs = require("fs");
    const products = JSON.parse(fs.readFileSync("products.json", "utf8"));
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    const server = http.createServer((req, res) => {
      const url = new URL(req.url, "http://localhost");
      const m = /^\/products\/([^/]+)$/.exec(url.pathname);
      if (req.method === "GET" && m) {
        if (!/^\d+$/.test(m[1])) return sendJson(res, 400, { error: "id must be a number" });
        const p = products.find((x) => x.id === Number(m[1]));
        if (!p) return sendJson(res, 404, { error: "Product " + m[1] + " not found" });
        return sendJson(res, 200, p);
      }
      sendJson(res, 404, { error: "Not found" });
    });
    …

    What it shows

    PASS GET /products/<id> answers that product
  7. 7Create: POST and 201

    Add an item, answer 201 Created with a Location header.

    The idea

    Ticket CL-407: the support team's task board moves to the API. First step: list the tasks and add new ones.

    POST /tasks with { "title": "Book the van" } creates a task. The server, not the caller, picks the id: one more than the highest id so far. A new task starts with done: false.

    The code

    const http = require("http");
    let tasks = [
      { id: 1, title: "Call the courier", done: false },
      { id: 2, title: "Reply to Mia", done: true },
    ];
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    async function readJson(req) {
      let body = "";
      for await (const chunk of req) body += chunk;
      return JSON.parse(body);
    }
    const server = http.createServer(async (req, res) => {
      if (req.method === "GET" && req.url === "/tasks") return sendJson(res, 200, tasks);
      if (req.method === "POST" && req.url === "/tasks") {
        const body = await readJson(req);
    …

    What it shows

    PASS POST /tasks answers 201 with the new task and its Location
  8. 8Update and delete

    PATCH changes part of an item; DELETE removes it with 204.

    The idea

    Ticket CL-408: on the task board, people tick tasks off and remove old ones.

    PATCH /tasks/2 with { "done": true } changes only the fields that are sent and answers the whole task. (PUT would replace the whole task.) Object.assign(task, changes) copies the sent fields onto it.

    The code

    const http = require("http");
    let tasks = [
      { id: 1, title: "Call the courier", done: false },
      { id: 2, title: "Reply to Mia", done: true },
    ];
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    async function readJson(req) {
      let body = "";
      for await (const chunk of req) body += chunk;
      return JSON.parse(body);
    }
    const server = http.createServer(async (req, res) => {
      const m = /^\/tasks\/(\d+)$/.exec(req.url);
      if (req.method === "GET" && req.url === "/tasks") return sendJson(res, 200, tasks);
      if (m && (req.method === "PATCH" || req.method === "DELETE")) {
    …

    What it shows

    PASS PATCH changes only the fields sent
  9. 9Check what comes in

    Never trust the body: 400 with a clear error.

    The idea

    Ticket CL-409: someone's script posted 2,000 empty tasks, and another sent a title the length of a book. The board is unusable. From now on the API checks every new task.

    Anything can arrive in a body: no JSON at all, a number instead of text, missing fields. JSON.parse throws on text that is not JSON, so wrap it in try/catch and answer 400. Then check each field and answer 400 with { error, field }, so the caller knows what to fix.

    The code

    const http = require("http");
    let tasks = [];
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    async function readJson(req) {
      let body = "";
      for await (const chunk of req) body += chunk;
      return JSON.parse(body);
    }
    const PRIORITIES = ["low", "normal", "high"];
    function check(body) {
      if (typeof body !== "object" || body === null) return { error: "The body must be a JSON object" };
      const title = typeof body.title === "string" ? body.title.trim() : "";
      if (title.length < 1 || title.length > 100) return { error: "title must be 1 to 100 characters", field: "title" };
      if (body.priority !== undefined && !PRIORITIES.includes(body.priority)) return { error: "priority must be low, normal or high", field: "priority" };
      return null;
    …

    What it shows

    PASS Text that is not JSON answers 400 and saves nothing
  10. 10When something breaks inside

    Catch the error, answer 500, keep the details in the log.

    The idea

    Ticket CL-410: when the stock database is slow, GET /stock/12 crashes the whole server and every customer gets nothing. The stock lookup is in stock-service.js (from the warehouse team): getStock(id) gives back a promise, and it can fail.

    In Node, an error nobody catches stops the whole program. In a server, catch errors around the work of each request: try { ... } catch (err) { ... } inside the handler, so one bad request cannot take the others down.

    The code

    const http = require("http");
    const { getStock } = require("./stock-service");
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    const server = http.createServer(async (req, res) => {
      try {
        const m = /^\/stock\/(\d+)$/.exec(req.url);
        if (req.method === "GET" && m) {
          const stock = await getStock(Number(m[1]));
          return sendJson(res, 200, stock);
        }
        sendJson(res, 404, { error: "Not found" });
      } catch (err) {
        console.error(err);
        sendJson(res, 500, { error: "Something went wrong. Try again later." });
      }
    …

    What it shows

    PASS A working lookup answers the stock
  11. 11Middleware

    Small steps that run before every route.

    The idea

    Ticket CL-411: support can't match customer complaints to the logs. Every answer must carry a request id, and the API must refuse bodies that are not JSON before any route sees them.

    Middleware is a function (req, res, next) that runs before the routes. It can add something (a header), stop the request (answer an error and not call next()), or pass it on with next(). The starter has a tiny runner: use(fn) adds a step, and every request goes through the steps in order, the routes last.

    The code

    const http = require("http");
    const crypto = require("crypto");
    const steps = [];
    const use = (fn) => steps.push(fn);
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    async function readJson(req) {
      let body = "";
      for await (const chunk of req) body += chunk;
      return JSON.parse(body);
    }
    let notes = [];
    function routes(req, res) {
      if (req.method === "GET" && req.url === "/notes") return sendJson(res, 200, notes);
      if (req.method === "POST" && req.url === "/notes") return readJson(req).then((b) => { notes.push(b.text); sendJson(res, 201, { text: b.text }); });
      sendJson(res, 404, { error: "Not found" });
    …

    What it shows

    PASS Every answer, even a 404, has a new X-Request-Id
  12. 12Let the shop front call the API

    CORS headers for the sites you allow, and preflight requests.

    The idea

    Ticket CL-412: the shop front at https://copperleaf.shop and the admin panel at https://admin.copperleaf.shop call the API from the browser. The browser blocks them until the API says those sites are allowed.

    A browser sends the page's site in the Origin header. The API allows it by answering with Access-Control-Allow-Origin set to that same origin, plus Vary: Origin (so caches keep one copy per site). An origin that is not on your list gets no such header, and the browser blocks it.

    The code

    const http = require("http");
    const ALLOWED = ["https://copperleaf.shop", "https://admin.copperleaf.shop"];
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    const server = http.createServer((req, res) => {
      const origin = req.headers.origin;
      const allowed = ALLOWED.includes(origin);
      if (allowed) {
        res.setHeader("Access-Control-Allow-Origin", origin);
        res.setHeader("Vary", "Origin");
      }
      if (req.method === "OPTIONS") {
        if (allowed) {
          res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE");
          res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        }
    …

    What it shows

    PASS Allowed origins get their own origin back, with Vary: Origin; others get no CORS header
  13. 13An access log

    One line per request, written when the answer is finished.

    The idea

    Ticket CL-413: ops wants an access log, access.log, with one line per request: method, path, status and how long it took, like GET /tasks 200 3ms.

    The status is known only when the answer is done, so log then: res.on("finish", () => { ... }) runs once the answer has been sent. Take the time with Date.now() when the request comes in, and again in finish.

    The code

    const http = require("http");
    const fs = require("fs");
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    const server = http.createServer((req, res) => {
      const start = Date.now();
      res.on("finish", () => {
        const line = req.method + " " + req.url + " " + res.statusCode + " " + (Date.now() - start) + "ms";
        fs.appendFile("access.log", line + "\n", (err) => {
          if (err) console.error(err);
        });
      });
      if (req.method === "GET" && req.url === "/tasks") return sendJson(res, 200, [{ id: 1, title: "Call the courier" }]);
      sendJson(res, 404, { error: "Not found" });
    });
    server.listen(3000, () => console.log("Listening on port 3000"));

    What it shows

    PASS Each request adds its line, with method, path and status
  14. 14Keep the data after a restart

    Save to a file on every change, load it at start.

    The idea

    Ticket CL-414: after last night's deploy, every task on the board was gone. The tasks lived only in memory, and a restart wipes memory.

    Until there is a database, save the list to tasks.json after every change, and load it when the server starts (an empty list when the file is not there yet).

    The code

    const http = require("http");
    const fs = require("fs");
    const { writeFile } = require("fs/promises");
    let tasks = fs.existsSync("tasks.json") ? JSON.parse(fs.readFileSync("tasks.json", "utf8")) : [];
    function sendJson(res, status, data) {
      res.writeHead(status, { "Content-Type": "application/json" });
      res.end(JSON.stringify(data));
    }
    async function readJson(req) {
      let body = "";
      for await (const chunk of req) body += chunk;
      return JSON.parse(body);
    }
    const server = http.createServer(async (req, res) => {
      if (req.method === "GET" && req.url === "/tasks") return sendJson(res, 200, tasks);
      if (req.method === "POST" && req.url === "/tasks") {
        const body = await readJson(req);
        const task = { id: tasks.reduce((top, x) => Math.max(top, x.id), 0) + 1, title: body.title, done: false };
    …

    What it shows

    PASS Tasks added before a restart are still there after it

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam