Capstone: JSON API
The spec
The JSON API serves a tiny notes collection over HTTP: list notes, read one note, and create a note. Every response is JSON with the right content type header.
Keep three routes and one in memory array for the whole lesson. Routing, JSON bodies, and status codes are the skills being practiced, not persistence. The program builds one note and prints its fields.
type Note = { id: number; text: string; }; const first: Note = { id: 1, text: "Buy milk" }; console.log(first.id, first.text);
1 Buy milk
node:http server sketch
createServer builds an HTTP server from a single request handler function. The handler receives the request and response objects with types filled in by context.
Answer every request with a 200 status and a JSON content type while sketching. Real routing lands in the next section, so the server shape stays visible first. The program listens on a free port on 127.0.0.1, answers its own request once and prints the status and the content type.
import { createServer, get } from "node:http"; const server = createServer(function (_req, res): void { res.writeHead(200, { "Content-Type": "application/json" }); res.end("{}"); }); server.listen(0, "127.0.0.1", function (): void { const address = server.address(); const port = typeof address === "object" && address !== null ? address.port : 0; get(`http://127.0.0.1:${port}/`, function (res): void { console.log(res.statusCode, res.headers["content-type"]); res.resume(); res.on("end", function (): void { server.close(); }); }); });
200 application/json
JSON routes
Routing maps the request URL to a handler name with a tiny function. Exact matches for a few paths beat a framework when the API has three endpoints.
Return a label such as notes or unknown and let the handler format the response. Unknown paths answer 404 later, but the mapping stays one pure function. The program routes one known path and prints the label.
function route(url: string): string { if (url === "/notes") { return "notes"; } return "unknown"; } const hit: string = route("/notes"); console.log(hit);
notes
Test with node:http client
Test the API with the get function from the same node:http module. No extra tooling is needed to prove that the server answers.
Point the client at the local address, read the status code, and assert the body parses. Start the server, run the client, then stop the server for a repeatable loop. The program starts the notes route, reads the list through the client and prints the status with the number of notes.
import { createServer, get } from "node:http"; type Note = { id: number; text: string; }; const notes: Array<Note> = [{ id: 1, text: "Buy milk" }]; const server = createServer(function (_req, res): void { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(notes)); }); server.listen(0, "127.0.0.1", function (): void { const address = server.address(); const port = typeof address === "object" && address !== null ? address.port : 0; get(`http://127.0.0.1:${port}/notes`, function (res): void { let body = ""; res.on("data", (chunk: Buffer) => { body += chunk; }); res.on("end", function (): void { const list = JSON.parse(body) as Array<Note>; console.log(res.statusCode, list.length); server.close(); }); }); });
200 1
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the request handler of
createServerreceive?Answer
The request and the response, typed by context
The handler writes the answer on the response object, and its two parameters are inferred from
createServer. -
Why is a tiny route function better than a framework here?
Answer
Three exact paths are one pure function, which is easy to test
The mapping stays one function with an obvious test, and no dependency enters the project.
-
What must every JSON answer carry?
Answer
The JSON content type header and a status code
The type tells the client how to read the body, and the status says how the request went.
-
Why listen on port zero in a test?
Answer
The system picks a free port, so two runs never collide
A fixed port fails when it is taken; port zero asks the system for a free one, read back from
server.address(). -
What does this program print?
type Note = { id: number; text: string }; const first: Note = { id: 1, text: "Buy milk" }; console.log(first.id, first.text);Answer
1 Buy milk
The two fields print in the order of the log call.
-
What does this program print?
function route(url: string): string { if (url === "/notes") { return "notes"; } return "unknown"; } console.log(route("/notes"), route("/other"));Answer
notes unknown
The first path matches and the second falls through to the default label.
-
What does this program print? ``
import { createServer, get } from "node:http"; const server = createServer((_req, res) => { res.writeHead(201, { "Content-Type": "application/json" }); res.end("{}"); }); server.listen(0, "127.0.0.1", () => { const address = server.address(); const port = typeof address === "object" && address !== null ? address.port : 0; get(http://127.0.0.1:${port}/, (res) => { console.log(res.statusCode); res.resume(); res.on("end", () => { server.close(); }); }); });``Answer
201
The handler writes the status 201, and the client reads it back.
-
What does this program print? ``
import { createServer, get } from "node:http"; const server = createServer((_req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify([{ id: 1 }, { id: 2 }])); }); server.listen(0, "127.0.0.1", () => { const address = server.address(); const port = typeof address === "object" && address !== null ? address.port : 0; get(http://127.0.0.1:${port}/notes, (res) => { let body = ""; res.on("data", (chunk) => { body += chunk; }); res.on("end", () => { const list = JSON.parse(body) as Array<{ id: number }>; console.log(res.statusCode, list.length); server.close(); }); }); });``Answer
200 2
The answer is a 200 with two notes, and the parsed list reports both.
-
What does the compiler say about this program?
type Note = { id: number; text: string }; const first: Note = { id: "1", text: "Buy milk" }; console.log(first);Answer
error TS2322: Type 'string' is not assignable to type 'number'.
The id is a number in the type, and the text in the object does not fit it.
-
What does the compiler say about this program?
import { get } from "node:http"; get("http://127.0.0.1/notes", function (res): void { const code: string = res.statusCode; console.log(code); });Answer
error TS2322: Type 'number | undefined' is not assignable to type 'string'.
A status code is a number and may be missing, so it cannot be stored in a plain string.
Article author: Arthur Isaev