WeCodeAcademy

Node.js Routing and JSON APIs

A REST API uses URLs and HTTP methods (GET, POST, ...) to work with data. This tiny API stores items in memory.

ExampleNode.js
const http = require("http");

const items = [{ id: 1, name: "Notebook" }];

const server = http.createServer((req, res) => {
  const send = (status, data) => {
    res.writeHead(status, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  };
  if (req.method === "GET" && req.url === "/items") return send(200, items);
  if (req.method === "POST" && req.url === "/items") {
    let body = "";
    req.on("data", (c) => (body += c));
    req.on("end", () => {
      const item = { id: items.length + 1, ...JSON.parse(body) };
      items.push(item);
      send(201, item);
    });
    return;
  }
  send(404, { error: "not found" });
});

server.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const created = await fetch(base + "/items", { method: "POST", body: JSON.stringify({ name: "Pen" }) });
  console.log(created.status, await created.json());
  const list = await fetch(base + "/items");
  console.log(list.status, (await list.json()).map((i) => i.name));
  const missing = await fetch(base + "/nope");
  console.log(missing.status);
  server.close();
});
Output
201 { id: 2, name: 'Pen' }
200 [ 'Notebook', 'Pen' ]
404

Frameworks such as Express make routing nicer (app.get('/items', ...)), but they build on exactly this request/response model.

Quick check

Which HTTP method is normally used to create something?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.