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 an in-memory map, so the example stays self-contained. (A real server handles requests concurrently, so a production version would guard the map with a lock and probably swap it for a database — the handlers would not change shape.)


Create and List

POST decodes the incoming JSON, 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.

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 Go program implementing the create and list part of a users REST API with a mux and an in-memory map: POST /users decodes JSON, assigns an id and answers 201 with the created user; GET /users answers with the JSON array of all users. Serve with httptest, create Ana and Ben, list them, and print every status and body.
Output: Go program and captured output

Read One, Replace, Delete

The {id} routes complete the set: read answers 200 or 404, replace decodes the new data into the existing id, 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), delete it, and fail to read it — every step with the correct status code.

Prompt
Write a Go 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 keeping the id, DELETE answers 204. Serve with httptest and run the full lifecycle — read, replace, delete, read again — printing each method, status and body.
Output: Go program and captured output