HTTP Methods, Status Codes and REST Routes
Design a small REST API for the tool library with the methods GET, POST, PUT and DELETE, return correct status codes such as 201, 204, 404 and 405, and test every route with a real client and curl.
In this lesson you will
- Map resources to URLs
- Use the right method for each action
- Return the right status code
- Test every route
About 28 minutes
One URL for each thing, one verb for each action
Kofi needs his app to list tools, add a new one, change one and remove one. REST is a convention for doing this over HTTP. The things the API manages, here tools, are resources, and each has a URL: /tools is the collection, /tools/2 is the second tool. The HTTP method says what to do with it: GET reads, POST creates, PUT replaces, PATCH changes part, and DELETE removes. Because everyone follows the same convention, a developer who has never seen Kofi’s API can guess how it works.
The status code tells the client what happened, and the right code matters, because clients and tools react to it. 200 means OK, 201 means created and should come with a Location header giving the URL of the new resource, 204 means success with no body, such as after a delete, 400 means the request itself was bad, 404 means the resource does not exist and 405 means that the URL exists but not for this method, with an Allow header that lists what is possible. Safe methods like GET must not change anything, and GET, PUT and DELETE are idempotent: repeating them has the same effect as doing them once, which makes retries safe.
| Method | Path | Action | Success status |
|---|---|---|---|
| GET | /tools | List | 200 |
| POST | /tools | Create | 201 + Location |
| GET | /tools/2 | Read one | 200 (404 if missing) |
| PUT | /tools/2 | Replace | 200 |
| DELETE | /tools/2 | Remove | 204 |
import threading, json, urllib.request, urllib.error, subprocess
from http.server import BaseHTTPRequestHandler, HTTPServer
tools = {1: {"id": 1, "name": "Drill"}, 2: {"id": 2, "name": "Ladder"}}
next_id = [3]
class H(BaseHTTPRequestHandler):
def send(self, code, obj=None, headers=None):
body = json.dumps(obj).encode() if obj is not None else b""
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
for k, v in (headers or {}).items(): self.send_header(k, v)
self.end_headers(); self.wfile.write(body)
def parts(self): return [p for p in self.path.split("/") if p]
def body(self):
n = int(self.headers.get("Content-Length", 0)); return json.loads(self.rfile.read(n) or b"{}")
def do_GET(self):
p = self.parts()
if p == ["tools"]: return self.send(200, list(tools.values()))
if len(p) == 2 and p[0] == "tools":
t = tools.get(int(p[1])) if p[1].isdigit() else None
return self.send(200, t) if t else self.send(404, {"error": "no such tool"})
self.send(404, {"error": "no such route"})
def do_POST(self):
if self.parts() != ["tools"]: return self.send(405, {"error": "method not allowed"}, {"Allow": "GET, PUT, DELETE"})
data = self.body()
if not data.get("name"): return self.send(400, {"error": "name is required"})
t = {"id": next_id[0], "name": data["name"]}; tools[t["id"]] = t; next_id[0] += 1
self.send(201, t, {"Location": "/tools/%d" % t["id"]})
def do_PUT(self):
p = self.parts()
if len(p) == 2 and p[1].isdigit() and int(p[1]) in tools:
tools[int(p[1])]["name"] = self.body().get("name", tools[int(p[1])]["name"]); return self.send(200, tools[int(p[1])])
self.send(404, {"error": "no such tool"})
def do_DELETE(self):
p = self.parts()
if len(p) == 2 and p[1].isdigit() and int(p[1]) in tools:
del tools[int(p[1])]; return self.send(204)
self.send(404, {"error": "no such tool"})
def log_message(self, *a): pass
srv = HTTPServer(("127.0.0.1", 0), H); base = "http://127.0.0.1:%d" % srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()
def call(method, path, obj=None):
req = urllib.request.Request(base + path, method=method, data=json.dumps(obj).encode() if obj is not None else None, headers={"Content-Type": "application/json"})
try:
r = urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
r = e
raw = r.read()
return r.status if hasattr(r, "status") else r.code, (json.loads(raw) if raw else None), dict(r.headers)
steps = [("GET", "/tools", None), ("POST", "/tools", {"name": "Sander"}), ("GET", "/tools/3", None), ("PUT", "/tools/3", {"name": "Orbital sander"}),
("DELETE", "/tools/1", None), ("GET", "/tools/1", None), ("POST", "/tools", {}), ("POST", "/tools/2", {"name": "x"}), ("GET", "/tools", None)]
log = []
for m, p, o in steps:
code, body, h = call(m, p, o)
extra = h.get("Location") or h.get("Allow") or ""
print(m.ljust(6), p.ljust(9), code, (json.dumps(body) if body is not None else "-")[:60], extra)
log.append([m, p, code, extra])
print("DATA " + json.dumps({"log": log, "final": call("GET", "/tools")[1]}))
srv.shutdown()
GET /tools 200 [{"id": 1, "name": "Drill"}, {"id": 2, "name": "Ladder"}]
POST /tools 201 {"id": 3, "name": "Sander"} /tools/3
GET /tools/3 200 {"id": 3, "name": "Sander"}
PUT /tools/3 200 {"id": 3, "name": "Orbital sander"}
DELETE /tools/1 204 -
GET /tools/1 404 {"error": "no such tool"}
POST /tools 400 {"error": "name is required"}
POST /tools/2 405 {"error": "method not allowed"} GET, PUT, DELETE
GET /tools 200 [{"id": 2, "name": "Ladder"}, {"id": 3, "name": "Orbital san
The program ran a nine-step conversation with the API. In order: GET /tools answered 200; POST /tools answered 201; GET /tools/3 answered 200; PUT /tools/3 answered 200; DELETE /tools/1 answered 204; GET /tools/1 answered 404; POST /tools answered 400; POST /tools/2 answered 405; GET /tools answered 200. Each status says what happened. The POST created tool 3 and returned 201 with the header Location: /tools/3, so the client knows where the new resource lives. The DELETE returned 204, an empty success, and the next GET for the same tool returned 404. A POST with no name was refused with 400, because the request was wrong, not the server. A POST to /tools/2 is a method that the URL does not support, which is 405, and the Allow header lists what the URL does support: GET, PUT, DELETE.
After the whole conversation the collection holds 2 tools: #2 Ladder, #3 Orbital sander. Tool 1 was deleted and tool 3 was created and then renamed by a PUT. Keep the rules of safe and idempotent methods in mind: repeating the PUT would give the same result, repeating the DELETE would now give 404 but not change the data, and repeating the POST would create another tool, which is why creation is not idempotent and why payment APIs add an idempotency key, as the API integration course shows.
Independent check: curl sent three of the requests to a second small server, and reported the status codes 201 for a POST with a name, 400 for a POST with an empty body, and 204 for a DELETE, the same codes that the Python client received for the same kinds of request. The final state of the collection is also easy to verify by simulation: start with tools 1 and 2, add 3, rename 3, remove 1, and you get tools 2 and 3.
Check by hand: the statuses in order are 200 (list), 201 (create), 200 (read), 200 (replace), 204 (delete), 404 (read the deleted), 400 (no name), 405 (POST on a single tool) and 200 (list again). Nine requests, and one status that is not in the 2xx range for each of the three kinds of error.
Returning 200 with an error message in the body breaks every client, proxy and monitor that reads status codes. Use 4xx when the client is wrong and 5xx when the server is.
Prefer DELETE /tools/2 to GET /deleteTool?id=2. A GET that changes data can be triggered by a link preview, a crawler or a prefetch.
Every program in this lesson was run while the course was written, with Python 3.13 and only its standard library (http.server, sqlite3, hashlib, hmac), with a real server on a free local port, and cross-checked with curl, openssl or a second implementation. Tools and versions change, so check the official documentation for current behaviour. REST is a style, not a strict standard, so projects differ. Check the API design guidelines that your team or provider publishes.
Practice
Add PATCH to change only the name. Add a query string /tools?name=Drill to filter the list. Make the API answer 415 when the Content-Type is not JSON, and test it with curl.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Which method creates a resource?
- GET
- DELETE
- POST
- HEAD
On the collection URL.
What does 201 mean?
- Not found
- Created
- Bad request
- No content
Send a Location header.
What does 405 mean?
- The URL does not exist
- The method is not allowed for this URL
- Server error
- Unauthorised
With an Allow header.
Which methods are idempotent?
- GET, PUT and DELETE
- POST only
- None
- All of them
Repeating them has the same effect as once.
Why not use GET to delete?
- GET must be safe and not change data
- GET is slower
- GET has no body
- It is not allowed in HTML
Crawlers and prefetch use GET.
Summary
- Resources get URLs and the method says what to do.
- Status codes tell the client what happened: 201, 204, 400, 404, 405.
- GET is safe, and GET, PUT and DELETE are idempotent.
- Test every route with a real client.
Questions
Is PUT or PATCH better for updates?
PUT replaces the whole resource and PATCH changes only some fields. Use PATCH for small edits and PUT when the client sends the full object.
Should URLs be plural?
Many teams use plural nouns for collections, such as /tools, and it is a matter of convention. Be consistent.
What is the difference between REST and GraphQL?
REST uses many URLs with fixed responses, GraphQL uses one URL where the client describes the data it wants. Both are used, and REST is the simpler place to start.
