Skip to main content

A Small, Complete API

Time to assemble the pieces: a users API with the five classic endpoints —

POST /users create · GET /users list · GET /users/{id} read one · PUT /users/{id} replace · DELETE /users/{id} remove.

The store is a Map in memory, so the example stays self-contained. Node.js runs your handlers one after another on a single thread, so nothing here needs locking; a real server would swap the Map for a database, and the handlers would not change shape.


Create and List

POST reads the incoming JSON from the request body, gives the user an id, stores it, and answers 201 with the created record — id included, so the client learns it. GET returns everyone as a JSON array.

The body does not arrive all at once, so a small readBody helper collects the chunks with for await before JSON.parse sees them.

POST /users and GET /users

Two creations, then the list: each POST answers 201 with the stored user, and the final GET shows both — the API's state grew with each request.

Prompt
Write a TypeScript program implementing the create and list part of a users REST API over node:http and an in-memory Map: POST /users parses the JSON body, assigns an id and answers 201 with the created user; GET /users answers with the JSON array of all users. Serve it on port 0, create Ana and Ben, list them, and print every status and body.
Output: TypeScript file and captured output

Read One, Replace, Delete

The {id} routes complete the set: read answers 200 or 404, replace takes the new data and keeps the id from the URL, delete answers 204. After the delete, the same GET that worked before honestly returns 404 — the resource is gone.

GET, PUT and DELETE on /users/{id}

The full life of one resource: read it, replace it (the response carries the new name Ana Maria), delete it, and fail to read it — every step with the correct status code.

Prompt
Write a TypeScript program implementing GET, PUT and DELETE for /users/{id} over an in-memory Map seeded with one user: GET answers 200 or 404 with JSON, PUT replaces the user but keeps the id from the URL, DELETE answers 204. Serve it on port 0 and run the full lifecycle — read, replace, delete, read again — printing each method, status and body.
Output: TypeScript file and captured output