Lesson 02 · 40 minutes
Build a notes API and call it with curl
- Map resources and methods to the right URL, status code and content type
- Build an in-memory notes API that sends and receives JSON
- Validate input on the server and refuse bad requests with a clear status
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
A mobile team wants to store short notes on your server, and they ask for "a small API". Last month a similar service accepted a 5 MB "note" and a body that was not JSON, and it answered 200 to both. Your task is to build the notes API on your own machine so that it accepts good requests and refuses each bad one with the right status code. Then you change its rules yourself, to prove that you understand them.
Recall
Lesson 1. Name the three parts of a web application. Which one keeps data after the program stops?
The client, the server and the database. The database keeps the data. The server only holds it while the program runs.
Lesson 1. Your server logs the line "GET /nothing HTTP/1.1" 404. What does it tell you?
A client asked for the path /nothing with the method GET, and the server answered with the status 404, not found.
The idea
A REST API treats data as resources with a URL. The HTTP method says what to do with the resource.
| Method | URL | Action | Success status |
|---|---|---|---|
| GET | /notes | List the notes | 200 |
| POST | /notes | Create a note | 201 |
| GET | /notes/1 | Read one note | 200 |
| PUT | /notes/1 | Replace a note | 200 |
| DELETE | /notes/1 | Delete a note | 204 (no body) |
The status code tells the client what happened. 2xx means success. 4xx means the client made a mistake: 400 bad request, 404 not found, 415 wrong content type. 5xx means the server failed. A client error must never be a 500.
JSON is the usual body. The Content-Type: application/json header says that the body is JSON, and the server must check it.
- Client → Server: POST /notes with a JSON body
- Server: check type, JSON and length
- Server → Client: 415 or 400 if a check fails
- Server → Notes store: save the note
- Server → Client: 201 and the new note
Worked example
1. Write the API
Create notes.py in ~/krlab/web-apis. Notes live in a Python dictionary, so they vanish when the server stops. The functions read_text and route hold all the input checks. Seven names are new:
do_GET,do_POST,do_PUTanddo_DELETEare the methods that the server calls for each HTTP method. You wrotedo_GETin lesson 1.self.headersholds the request headers, andself.rfile.read(n)readsnbytes of the request body. The headerContent-Lengthsays how many bytes the body has.max(0, ...)turns a negative length into 0:readwith a negative number would wait for ever.self.headers.get_content_type()returns the type of the body without its parameters, soapplication/json; charset=utf-8counts asapplication/json, and it returnstext/plainwhen the header is missing.json.loadsturns JSON text into a Python value. It raisesValueErrorwhen the text is not JSON.re.fullmatchchecks that a whole string fits a regular expression, a short pattern. Here[0-9]{1,9}means "one to nine digits".1 <= len(text) <= 200is true only when both comparisons are true: the text has at least 1 and at most 200 characters.isinstance(text, str)asks whether a value is a string, so a client cannot send a number or a list in its place.- The word
globallets a method changeNEXT_ID, which lives outside the method. - A
returnwith no value leaves the method at once. The text in triple quotes under adefis a docstring, a note for the reader.
How to read route:
- The pattern
/notes(?:/([0-9]{1,9}))?starts with the fixed text/notes. - The group
(?:...)groups its content without saving it, and the?after it means "zero or one time". The inner(...)saves the digits. - For the path
/notes/12the matchmis true andm[1]is"12". For/notes,m[1]isNone, because the group did not match. For/notes/abc,mitself isNone. routereturns a pair (a tuple of two values): "is the path valid?" and "which id?". Indo_PUT,[1]takes the second value of the pair.
notes.py
import json, re
from http.server import BaseHTTPRequestHandler, HTTPServer
NOTES = {} # id -> text, kept in memory
NEXT_ID = 1
class Handler(BaseHTTPRequestHandler):
def reply(self, status, obj=None):
data = json.dumps(obj).encode() if obj is not None else b""
self.send_response(status)
if data:
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def read_text(self):
"""Return the validated note text, or None after sending an error."""
if self.headers.get_content_type() != "application/json":
self.reply(415, {"error": "send application/json"})
return None
try:
size = max(0, int(self.headers.get("Content-Length", 0)))
body = json.loads(self.rfile.read(size))
text = body["text"]
except (ValueError, KeyError, TypeError):
self.reply(400, {"error": "body must be JSON with a text field"})
return None
if not isinstance(text, str) or not 1 <= len(text) <= 200:
self.reply(400, {"error": "text must be a string of 1 to 200 characters"})
return None
return text
def route(self):
"""Return (path is valid, note id or None). Only digits are an id."""
m = re.fullmatch(r"/notes(?:/([0-9]{1,9}))?", self.path)
if m is None:
return False, None
if m[1] is None:
return True, None
return True, int(m[1])
def do_GET(self):
valid, nid = self.route()
if not valid:
self.reply(404, {"error": "not found"})
elif nid is None:
self.reply(200, NOTES)
elif nid in NOTES:
self.reply(200, {"id": nid, "text": NOTES[nid]})
else:
self.reply(404, {"error": "no such note"})
def do_POST(self):
global NEXT_ID
valid, nid = self.route()
if not valid or nid is not None:
self.reply(404, {"error": "not found"})
return
text = self.read_text()
if text is not None:
NOTES[NEXT_ID] = text
self.reply(201, {"id": NEXT_ID, "text": text})
NEXT_ID += 1
def do_PUT(self):
nid = self.route()[1]
if nid not in NOTES:
self.reply(404, {"error": "no such note"})
return
text = self.read_text()
if text is not None:
NOTES[nid] = text
self.reply(200, {"id": nid, "text": text})
def do_DELETE(self):
nid = self.route()[1]
if nid not in NOTES:
self.reply(404, {"error": "no such note"})
return
del NOTES[nid]
self.reply(204)
HTTPServer(("127.0.0.1", 8300), Handler).serve_forever()2. Start it
python3 notes.pyUse a second terminal for the rest (type cd ~/krlab/web-apis first). Put the address in a shell variable H to save typing; $H then stands for the address.
H=http://127.0.0.1:83003. Create a note
-X POST sets the method. -d (data) sets the body. -H adds a header. The status 201 Created means that the server made a new resource.
curl -si -X POST $H/notes -H 'Content-Type: application/json' -d '{"text":"buy milk"}'HTTP/1.0 201 Created
Server: BaseHTTP/0.6 Python/3.14.4
Date: Sat, 21 Nov 2026 08:34:52 GMT
Content-Type: application/json
Content-Length: 29
{"id": 1, "text": "buy milk"}4. Read, change and delete it
PUT replaces a note. DELETE removes it. The status 204 No Content means success with no body. The option -w (write out) prints text after the body: '\n' is a new line, and '[%{http_code}]\n' is the status in brackets.
curl -s -w '\n' $H/notes
curl -s -w '\n' -X PUT $H/notes/1 -H 'Content-Type: application/json' -d '{"text":"buy oat milk"}'
curl -s -w '[%{http_code}]\n' -X DELETE $H/notes/1
curl -s -w '[%{http_code}]\n' $H/notes/1{"1": "buy milk"}
{"id": 1, "text": "buy oat milk"}
[204]
{"error": "no such note"}[404]The DELETE answer has no body, so only the status shows. The last call proves that the note is gone.
5. Send input that must be refused
Each request below is wrong in a different way. The status 400 Bad Request means that the request is wrong, and 415 Unsupported Media Type means that the body has a type that the server does not accept.
curl -s -w ' [%{http_code}]\n' -X POST $H/notes -H 'Content-Type: application/json' -d '{"text":""}'
curl -s -w ' [%{http_code}]\n' -X POST $H/notes -d '{"text":"x"}'
curl -s -w ' [%{http_code}]\n' -X POST $H/notes -H 'Content-Type: application/json' -d 'not json'
curl -s -w ' [%{http_code}]\n' $H/notes/abc{"error": "text must be a string of 1 to 200 characters"} [400]
{"error": "send application/json"} [415]
{"error": "body must be JSON with a text field"} [400]
{"error": "not found"} [404]An empty text, a wrong content type, a body that is not JSON and an id that is not a number each get a clear 4xx. None of them crashes the server. Read route: it accepts an id only when it matches 1 to 9 digits, so abc is a 404 and not a Python error.
6. Look at the log
Stop the server with Ctrl+C and read its terminal. Every call has a line with its status, for example "POST /notes HTTP/1.1" 400 -. Your own 4xx lines are the first signal that someone sends bad input. A server that answers 200 to everything hides that signal.
Your turn
The mobile team changes the rules: a note may have at most 20 characters, and a text that holds only spaces is not a note. Change your own notes.py. There are no steps here. The Python method strip() removes the spaces at both ends of a string.
- Change
read_textso that it refuses a text of more than 20 characters, and a text that is empty afterstrip(). Both get status 400. Update the error message too. - Stop the server, start it again (the notes are in memory, so the list is empty) and send these five POST requests in this order: a text of exactly 20 letters
a, a text of 21 lettersa, a text of three spaces, the textband the textc. - Delete the note with id 1, then list all notes.
Last, send the text b again and read the id in the answer. Refused requests did not use an id, so the id is the next free one.
Check yourself
Why does the API return 415 and not 400 when the content type is wrong?
Both are client errors, but 415 says exactly what is wrong: the server does not accept this media type. A precise code lets a client program fix its request without a person reading the message.
A client sends text of 5,000 characters. Which check refuses it, and why must the server do it?
The check 1 <= len(text) <= 200 in read_text. The server must do it because a client check can be skipped; only the server controls what it stores.
What is wrong with answering "200 OK" and {"error": "no such note"} for a missing note?
The status is part of the contract. Clients, caches and monitoring tools read the status code first. A 200 for a failure makes errors invisible to them. Use 404.
Field notes
- Validate by allowing, not by blocking: define what a good value is (type, length, range, pattern) and refuse the rest. Blocking known bad strings always misses something. This is OWASP Top 10 "Injection" prevention at the first line.
- Put a limit on the size of the body before you read it. This server reads whatever positive
Content-Lengthsays; lesson 7 adds the limit and refuses a bad length. The OWASP API Security Top 10 names this risk "Unrestricted Resource Consumption". - Send errors in one fixed shape and never include a stack trace or an internal path in them. A detailed error helps the attacker more than the user (OWASP Top 10 "Security Misconfiguration").
PUTreplaces a whole resource and must give the same result when repeated.POSTmay create a new resource each time. A client that retries after a timeout relies on this.