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.

One PHP-shaped decision: each request runs the router script fresh, so the data cannot live in a variable between requests. Real APIs keep state in a database; here a small JSON file plays that role — the router loads it, changes it, saves it back. The handlers would keep their shape if the file were swapped for a real database.


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 PHP script implementing the create and list part of a users REST API with a router script and a JSON file as the store: POST /users decodes the body, assigns an id and answers 201 with the created user; GET /users answers with the JSON array of all users. Serve it with the built-in server, create Ana and Ben, list them, and print every status and body.
Output: PHP script

Read One, Replace, Delete

The /users/{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 PHP script implementing GET, PUT and DELETE for /users/{id} over a JSON file store seeded with one user: GET answers 200 or 404 with JSON, PUT replaces the user keeping the id, DELETE answers 204. Serve it with the built-in server and run the full lifecycle - read, replace, delete, read again - printing each method, status and body.
Output: PHP script