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 handler class routes by verb for you: the server calls do_GET for a GET, do_POST for a POST, do_DELETE for a DELETE — one method per verb. 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 Python program with a notes handler answering GET /notes with 200 and a list line, POST /notes with 201 and a Location header, and DELETE /notes/3 with 204 and an empty body. Serve on a free port, send the three requests and print each method, status code and any Location header or body.
Output: complete Python program

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 read-only route is 405 Method Not Allowed — here answered by a tiny do_DELETE. (Leave that method out entirely and http.server answers 501 Unsupported method on its own — writing the 405 yourself is the more precise REST answer.)

On the client side, urllib raises HTTPError for every 4xx and 5xx answer instead of returning it quietly — the error object still carries the status code and the body.

200, 404 and 405

The existing note returns 200 with data, the missing one 404 with a JSON error, and the DELETE is refused with 405. The client catches HTTPError and reads the error bodies from it.

Prompt
Write a Python program with a GET /notes/{id} handler answering 200 with JSON for an existing note, 404 with a JSON error body for a missing one, and 405 for any DELETE. Serve on a free port, send the three requests with urllib, catching HTTPError to read the error bodies, and print all three results.
Output: complete Python program