Skip to main content

Say What You Mean

A REST API talks through two vocabularies. The method says what the client wants: GET read, POST create, PUT replace, PATCH change a part, DELETE remove. The status code says how it went: 2xx success, 4xx the client's mistake, 5xx the server's.

A detail worth knowing: PUT is idempotent — sending it twice ends the same as once. POST is not: two POSTs create two resources.


The Right Method

The router reads the verb from $_SERVER["REQUEST_METHOD"] and sends each one to its own branch. Creation answers 201 Created and points at the new resource with a Location header; deletion answers 204 No Content — success with nothing to say.

GET, POST and DELETE on one resource

Three verbs, three answers: the list comes back with 200, the creation with 201 and a Location, the deletion with 204 and an empty body.

Prompt
Write a PHP script whose router checks $_SERVER["REQUEST_METHOD"] and handles GET /notes (200 with a list line), POST /notes (201 with a Location header) and DELETE /notes/{id} (204, empty body). Serve it with the built-in server, send the three requests and print each method, status code and any Location header or body.
Output: PHP script

The Right Status Code

Errors deserve precision too: a missing resource is 404 Not Found (with a JSON error body so machines can read it), and a wrong verb on a known path is 405 Method Not Allowed — with an Allow header naming the verbs that would work. The router script answers both itself, picking the status with http_response_code().

200, 404 and 405

The existing note returns 200 with data, the missing one 404 with a JSON error, and the DELETE on a GET-only route is refused with 405 and an Allow: GET header.

Prompt
Write a PHP script whose GET /notes/{id} handler returns 200 with JSON for an existing note, 404 with a JSON error body for a missing one, and answers any other method with 405 plus an Allow: GET header. Serve it with the built-in server, request an existing note, a missing note, and send a DELETE to show the 405 with its Allow header. Print all three results.
Output: PHP script