Plain-Text Notes CRUD API and Black-Box Testing
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Problem Statement
Complete two related backend engineering parts:
- In-memory plain-text CRUD service (
NotesAPI): implement a framework-independent HTTP request routerNotesAPI(max_bytes=10_000)whosehandle(method, path, headers=None, body=b"") -> Responsemethod manages text records while accepting raw plain-text request bodies (Content-Type: text/plain) and returning JSON payloads on every response (Content-Type: application/json), including errors. - Specification-driven (black-box) unit testing: design tests for a function or service when only its public contract is known and its source code is hidden, maximizing coverage across valid equivalence classes, exact boundaries, error paths, and invariants.
NotesAPI Specification
Every call to handle(method, path, headers=None, body=b"") returns Response(status, body, headers) where body is a JSON-serializable dict and headers includes "Content-Type": "application/json":
POST /items— RequiresContent-Type: text/plain(matched case-insensitively on both header name and media type; an optionalcharsetparameter is permitted only ifutf-8,utf8, orus-ascii, case-insensitive and optionally quoted). Validateslen(body) <= max_bytes, decodes bytes (asciiwhencharset=us-ascii, otherwiseutf-8), rejects empty or whitespace-only strings (while preserving leading/trailing whitespace on non-empty text), assigns a monotonically increasing integer ID starting at1, and returns201with{"message": "created", "id": n}plus header"Location": f"/items/{n}".GET /items/{id}— Returns200with{"id": n, "content": "..."}when itemnexists, or404with{"message": "item not found"}.PUT /items/{id}— ValidatesContent-Type,charset, byte size, decoding, and non-empty text first; if itemnexists, replaces its content and returns200with{"message": "updated", "id": n}, otherwise returns404with{"message": "item not found"}. FailedPUTcalls must leave existing stored text untouched.DELETE /items/{id}— Deletes itemnand returns200with{"message": "deleted", "id": n}, or404with{"message": "item not found"}if absent. Deleted IDs are never reused by laterPOSTrequests.
Routing, Validation & Concurrency Rules
- Strip query strings (e.g.,
?detail=1) and normalize leading/trailing slashes before matching routes. - Any path other than
/itemsor/items/{id}returns404({"message": "..."}). - Unsupported HTTP verbs on
/itemsreturn405with header"Allow": "POST"; unsupported verbs on/items/{id}return405with"Allow": "GET, PUT, DELETE". - Path
{id}must be a positive ASCII base-10 integer (>= 1); zero, negative values, non-digits, non-ASCII digit characters, or excessively long digit strings return400. - On
POSTandPUT, missing or non-text/plainmedia types or unsupportedcharsetvalues return415;len(body) > max_bytesreturns413; invalid byte sequences for the active encoding or empty/whitespace-only text return400. - Concurrent calls to
handlefrom multiple threads must never issue duplicate IDs or corrupt stored entries.
Examples
Example 1
Input:
api = NotesAPI()
1) api.handle("POST", "/items", {"Content-Type": "text/plain"}, b"inspect track 4")
2) api.handle("GET", "/items/1")
3) api.handle("PUT", "/items/1", {"Content-Type": "text/plain"}, b"track 4 cleared")
4) api.handle("DELETE", "/items/1")
5) api.handle("POST", "/items", {"Content-Type": "text/plain"}, b"check signal 9")
Output:
1) status=201, body={"message": "created", "id": 1}, headers["Location"]="/items/1"
2) status=200, body={"id": 1, "content": "inspect track 4"}
3) status=200, body={"message": "updated", "id": 1}
4) status=200, body={"message": "deleted", "id": 1}
5) status=201, body={"message": "created", "id": 2}
Creating the first note stores "inspect track 4" at ID 1 and sets Location: /items/1. After reading, updating, and deleting item 1, the next POST receives ID 2 because deleted IDs are never recycled.
Example 2
Input:
api = NotesAPI(max_bytes=8)
1) api.handle("POST", "/items", {"content-type": 'Text/Plain; charset="UTF-8"'}, "gate Δ".encode("utf-8"))
2) api.handle("PUT", "/items/1", {"Content-Type": "application/json"}, b'{"note":"x"}')
3) api.handle("PUT", "/items/1", {"Content-Type": "text/plain"}, b"123456789")
4) api.handle("GET", "/items/1")
Output:
1) status=201, body={"message": "created", "id": 1}
2) status=415, body={"message": "Content-Type must be text/plain"}
3) status=413, body={"message": "content must be at most 8 bytes"}
4) status=200, body={"id": 1, "content": "gate Δ"}
"gate Δ" uses 7 UTF-8 bytes (5 ASCII bytes plus 2 bytes for 'Δ'), which satisfies max_bytes = 8. Both invalid PUT requests fail (415 for JSON media type and 413 for 9 > 8 bytes) without mutating item 1.
Example 3
Input:
api = NotesAPI()
1) api.handle("GET", "/items")
2) api.handle("GET", "/items/0")
3) api.handle("GET", "/archive")
Output:
1) status=405, headers["Allow"]="POST"
2) status=400
3) status=404
GET is not supported on the collection path /items (405 with Allow: POST), 0 is not a positive integer ID (400), and /archive is not a valid endpoint (404).
Constraints
1 <= max_bytes <= 10^6(default10_000bytes; enforced on raw UTF-8/ASCII byte length, inclusive).methodis an ASCII HTTP verb string (matched case-insensitively).headersisNoneor aDict[str, str]with arbitrary header-name casing.- Every response
bodymust be JSON-serializable and paired with"Content-Type": "application/json".
Step-by-step walkthrough
Understand both tasks and lock down the API contract
This question pairs two foundational backend skills:
- Task 1 (REST CRUD API): build Create, Read, Update, and Delete endpoints for text notes where incoming request bodies are raw plain text (
Content-Type: text/plain), while every outgoing response — both successes and errors — is JSON (Content-Type: application/json). - Task 2 (Black-box unit testing): design unit tests for a function or service when you only know its specification (public contract) and cannot read its source code.
Because Task 1's own test suite is a live example of Task 2, we start by writing an explicit specification table. Every rule in this table becomes both a branch in our code and a test case later:
Method & Path Request Body Success Response Error Responses ------------------- -------------- ----------------------------------------- ----------------------------------- POST /items text/plain 201 {"message": "created", "id": n} 415 wrong Content-Type / charset + Header Location: /items/n 413 > max_bytes, 400 empty/bad UTF-8 GET /items/{id} (none) 200 {"id": n, "content": "..."} 400 invalid id, 404 missing item PUT /items/{id} text/plain 200 {"message": "updated", "id": n} 400, 404, 413, 415 DELETE /items/{id} (none) 200 {"message": "deleted", "id": n} 400 invalid id, 404 missing item Known path, bad verb (any) — 405 + Allow header (e.g. Allow: POST) Any other path (any) — 404 {"message": "route not found"}Four HTTP design choices are worth explaining up front:
200 OKinstead of204 No ContentonDELETE: HTTP204forbids a response body, whereas the prompt requires JSON on all responses ({"message": "deleted", "id": 1}).PUTupdates existing items only (404if missing): the server owns ID assignment (1, 2, 3, …), so allowing clients to invent/items/999viaPUTwould collide with future server-assigned IDs.- IDs are never reused after deletion: if item
2is deleted, the next created note gets ID3, preventing stale links to/items/2from silently displaying someone else's new note. - Validation order on
PUT /items/{id}: check HTTP verb (405) -> ID syntax (400) ->Content-Typeand body (415/413/400) -> item existence (404), rejecting malformed requests before touching storage.
- Task 1 (REST CRUD API): build Create, Read, Update, and Delete endpoints for text notes where incoming request bodies are raw plain text (
Separate pure routing logic from the HTTP socket server
Instead of tangling business rules inside socket callbacks, isolate the entire API inside a pure method
NotesAPI.handle(method, path, headers, body) -> Response, and attach Python'shttp.serveras a thin outer adapter:HTTP Client (curl / browser) │ raw TCP bytes ▼ Thin HTTP Adapter: serve() <-- parses Content-Length, writes JSON bytes │ (method, path, headers, body) ▼ Pure Core: NotesAPI.handle(...) <-- unit tests call here directly (microseconds!) │ threading.Lock ▼ In-Memory Store: {_items, _next_id}Why this separation helps both production code and tests:
- Unit tests call
api.handle(...)directly in memory — no open TCP ports, no background server threads, and thousands of assertions finish in milliseconds. - Every response goes through
json_response(...)anderror(...), making it impossible for any code path to accidentally return plain text or HTML.
from typing import Any, Dict, NamedTuple, Optional, Tuple import json import threading MAX_CONTENT_BYTES = 10_000 # Accepted charset parameter values; US-ASCII is strict 7-bit text and UTF-8 covers full Unicode ACCEPTED_CHARSETS = {"utf-8", "utf8", "us-ascii"} class Response(NamedTuple): # HTTP status code (e.g., 200, 201, 400, 404, 405, 413, 415) status: int # JSON-serializable payload dict, e.g. {"id": 1, "content": "inspect track 4"} or {"message": "..."} body: Dict[str, Any] # Response HTTP headers; always includes {"Content-Type": "application/json"} headers: Dict[str, str] def json_response(status: int, body: Dict[str, Any], extra_headers: Optional[Dict[str, str]] = None) -> Response: """Build a Response whose Content-Type is always application/json.""" headers = {"Content-Type": "application/json"} if extra_headers: headers.update(extra_headers) return Response(status, body, headers) def error(status: int, message: str, extra_headers: Optional[Dict[str, str]] = None) -> Response: """Build a standard JSON error Response of the shape {"message": "..."}.""" return json_response(status, {"message": message}, extra_headers)- Unit tests call
Parse headers and validate text/plain request bodies
Real HTTP clients frequently send
Content-Type: Text/Plain; charset="UTF-8"rather than the bare lowercase string"text/plain". A naive checkheaders.get("Content-Type") == "text/plain"wrongly rejects valid requests and misses lowercase header names like"content-type".We split the header on
";"to extract the lowercase media type and anykey=valueparameters, then run five validation checks in_text_bodyfrom cheapest to most specific:Incoming body bytes ──► 1. media_type != "text/plain"? ──► 415 Unsupported Media Type ──► 2. charset not UTF-8 / US-ASCII? ──► 415 Unsupported Media Type ──► 3. len(body) > max_bytes? ──► 413 Content Too Large ──► 4. invalid bytes for charset? ──► 400 Bad Request ──► 5. empty or whitespace-only string? ──► 400 Bad Request ──► Valid text string!Notice step 3 checks
len(body)in bytes before decoding: in UTF-8,"gate Δ"has 6 characters (g,a,t,e,' ','Δ') but 7 bytes (67 61 74 65 20 ce 94), so withmax_bytes = 8,"gate Δ"passes (7 <= 8) whileb"123456789"(9bytes) returns413. Also notice step 4 decodes strict 7-bit"ascii"when the client explicitly declarescharset=us-ascii, and full"utf-8"otherwise.def parse_media_type(value: Optional[str]) -> Tuple[str, Dict[str, str]]: """Split 'Text/Plain; charset="UTF-8"' into ('text/plain', {'charset': 'utf-8'}).""" if not value: return "", {} parts = value.split(";") # MIME type/subtype tokens are case-insensitive in HTTP (RFC 9110) media_type = parts[0].strip().lower() params: Dict[str, str] = {} for part in parts[1:]: if "=" in part: name, _, param_value = part.partition("=") clean_name = name.strip().lower() clean_value = param_value.strip().strip('"').lower() params[clean_name] = clean_value return media_type, paramsParse item IDs safely and route requests
Before touching the dictionary of notes,
handlenormalizes header names to lowercase, strips any query string (?verbose=1), strips leading/trailing slashes (/items/becomes["items"]), and dispatches by path segments:["items"]: allowsPOST; any other method gets405 Method Not Allowedwith headerAllow: POST.["items", raw_id]: allowsGET,PUT,DELETE(else405withAllow: GET, PUT, DELETE), then validatesraw_idviaparse_id.- Anything else (such as
/notesor/items/1/extra): returns404.
parse_idguards against three classic Python edge cases:- Unicode digits:
"²".isdigit()returnsTruein Python, so we checktext.isascii() and text.isdigit(). - Huge digit strings: since Python 3.11,
int("9" * 5000)raisesValueError(limit 4,300 digits) to block denial-of-service attacks; catchingValueErrorconverts that crash into a clean400JSON error. - Zero:
"0"passesisdigit(), so we checkvalue <= 0.
def parse_id(text: str) -> Optional[int]: """Parse a positive ASCII decimal integer ID ('12' -> 12), or return None if invalid.""" # Check isascii() alongside isdigit() because Unicode superscripts like '²' pass isdigit() if not (text.isascii() and text.isdigit()): return None try: value = int(text) except ValueError: # Python 3.11+ raises ValueError above 4,300 digits to block quadratic int-conversion DoS return None if value <= 0: return None return valueImplement thread-safe CRUD operations and the HTTP adapter
When a threaded server handles two simultaneous
POST /itemsrequests, both threads could readself._next_id == 1at the same instant and overwrite each other unless guarded by athreading.Lock. We holdself._lockonly around the fast O(1) dictionary and counter operations — never during body decoding or validation — so threads do not block each other unnecessarily.In
serve(),Handlerreads at mostapi.max_bytes + 1bytes from the socket stream: reading 1 extra byte is enough forapi.handle(...)to seelen(body) > max_bytesand return413without letting a gigabyte upload exhaust RAM.POST /items Content-Type: text/plain "inspect track 4" -> 201 {"message": "created", "id": 1} GET /items/1 -> 200 {"id": 1, "content": "inspect track 4"} PUT /items/1 Content-Type: application/json '{"note": "x"}' -> 415 {"message": "Content-Type must be text/plain"} GET /items/1 -> 200 {"id": 1, "content": "inspect track 4"} (unchanged!) PUT /items/1 Content-Type: text/plain "track 4 cleared" -> 200 {"message": "updated", "id": 1} DELETE /items/1 -> 200 {"message": "deleted", "id": 1} POST /items Content-Type: text/plain "check signal 9" -> 201 {"message": "created", "id": 2} (id 1 not reused!)Task 2: a systematic playbook for black-box unit testing
When you must test a function or API without seeing its implementation, you cannot rely on line or branch coverage of internal
ifstatements. Instead, treat the specification as a checklist and build confidence across six orthogonal layers.Suppose the hidden function's specification is:
split_bill(total_cents: int, people: int) -> List[int]returns a list ofpeoplenon-negative integers summing tototal_centswhose max and min differ by at most1, and raisesValueErrorifpeople < 1ortotal_cents < 0.- Equivalence partitioning (group inputs into classes governed by the same rule, picking one clear test per class):
- Divides evenly (
100cents across4people ->[25, 25, 25, 25]). - Leaves a remainder (
100cents across3people -> sorted shares[33, 33, 34]). - Fewer cents than people (
2cents across5people -> sorted shares[0, 0, 0, 1, 1]).
- Divides evenly (
- Boundary-value analysis (test exact cutoffs where off-by-one
<vs<=bugs hide):- Valid minimums:
total_cents = 0,people = 1(just inside the boundary). - Invalid neighbors:
total_cents = -1,people = 0,people = -3(one step across the boundary). - For our API:
len(body) == max_bytes(201) vsmax_bytes + 1(413);id = "1"vsid = "0".
- Valid minimums:
- Failure modes and state-preservation invariants:
- Assert exact exception types (
ValueError, notZeroDivisionErrorwhenpeople = 0) or exact HTTP status codes (400vs404vs415). - For stateful systems like
NotesAPI, assert that failed writes leave stored state untouched (for example, a400or415PUT /items/1does not erase the existing note).
- Assert exact exception types (
- Property-based & metamorphic assertions (when a spec permits multiple valid outputs):
- The spec does not say who gets the extra cent (
[34, 33, 33]and[33, 33, 34]are both valid!). Assertingsplit_bill(100, 3) == [34, 33, 33]would over-specify and fail a valid implementation. Assertlen(res) == people,sum(res) == total_cents,min(res) >= 0, andmax(res) - min(res) <= 1(or comparesorted(res)). - Check metamorphic relations (how outputs must relate when inputs transform): adding
peoplecents (total_cents + people) must increase every sorted share by exactly1.
- The spec does not say who gets the extra cent (
- Reference-model (differential) testing:
- For stateful APIs, run hundreds of random
(create, read, update, delete)sequences against bothNotesAPIand a tiny 20-line plain-dict reference model, asserting identical status codes and JSON bodies at every step.
- For stateful APIs, run hundreds of random
- Test isolation and mutation thinking:
- Structure every test as Arrange -> Act -> Assert with a fresh instance per test so one failure never cascades into later tests. Mentally invent 3 realistic buggy implementations (e.g., dumping the whole remainder on person
0, forgettingpeople == 0, or counting characters instead of UTF-8 bytes) and verify your suite catches every one.
- Structure every test as Arrange -> Act -> Assert with a fresh instance per test so one failure never cascades into later tests. Mentally invent 3 realistic buggy implementations (e.g., dumping the whole remainder on person
import random def run_black_box_split_bill_suite(split_bill): """Example black-box test suite structured by behavior against any split_bill implementation.""" # 1. Happy path + remainder distribution (check sorted multiset, not index order) assert split_bill(100, 4) == [25, 25, 25, 25] assert sorted(split_bill(100, 3)) == [33, 33, 34] # 2. Exact valid boundaries: zero cents, single person, fewer cents than people assert split_bill(0, 3) == [0, 0, 0] assert split_bill(7, 1) == [7] assert sorted(split_bill(2, 5)) == [0, 0, 0, 1, 1] # 3. Invalid boundaries must raise ValueError (not ZeroDivisionError) for bad_total, bad_people in [(10, 0), (10, -2), (-1, 3), (-1, 0)]: try: split_bill(bad_total, bad_people) raise AssertionError(f"Expected ValueError for {(bad_total, bad_people)}") except ValueError: pass # 4. Property + metamorphic checks across 500 randomized inputs rng = random.Random(0) for _ in range(500): total = rng.randint(0, 100_000) people = rng.randint(1, 50) shares = split_bill(total, people) assert len(shares) == people assert sum(shares) == total assert min(shares) >= 0 and max(shares) - min(shares) <= 1 # Metamorphic check: adding 1 cent per person shifts every sorted share up by 1 raised = split_bill(total + people, people) assert sorted(raised) == [s + 1 for s in sorted(shares)]- Equivalence partitioning (group inputs into classes governed by the same rule, picking one clear test per class):
Complete solution
from typing import Any, Dict, NamedTuple, Optional, Tuple import json import threading MAX_CONTENT_BYTES = 10_000 # Accepted charset parameter values; US-ASCII is strict 7-bit text and UTF-8 covers full Unicode ACCEPTED_CHARSETS = {"utf-8", "utf8", "us-ascii"} class Response(NamedTuple): # HTTP status code (e.g., 200, 201, 400, 404, 405, 413, 415) status: int # JSON-serializable payload dict, e.g. {"id": 1, "content": "inspect track 4"} or {"message": "..."} body: Dict[str, Any] # Response HTTP headers; always includes {"Content-Type": "application/json"} headers: Dict[str, str] def json_response(status: int, body: Dict[str, Any], extra_headers: Optional[Dict[str, str]] = None) -> Response: """Build a Response whose Content-Type is always application/json.""" headers = {"Content-Type": "application/json"} if extra_headers: headers.update(extra_headers) return Response(status, body, headers) def error(status: int, message: str, extra_headers: Optional[Dict[str, str]] = None) -> Response: """Build a standard JSON error Response of the shape {"message": "..."}.""" return json_response(status, {"message": message}, extra_headers) def parse_media_type(value: Optional[str]) -> Tuple[str, Dict[str, str]]: """Split 'Text/Plain; charset="UTF-8"' into ('text/plain', {'charset': 'utf-8'}).""" if not value: return "", {} parts = value.split(";") # MIME type/subtype tokens are case-insensitive in HTTP (RFC 9110) media_type = parts[0].strip().lower() params: Dict[str, str] = {} for part in parts[1:]: if "=" in part: name, _, param_value = part.partition("=") clean_name = name.strip().lower() clean_value = param_value.strip().strip('"').lower() params[clean_name] = clean_value return media_type, params def parse_id(text: str) -> Optional[int]: """Parse a positive ASCII decimal integer ID ('12' -> 12), or return None if invalid.""" # Check isascii() alongside isdigit() because Unicode superscripts like '²' pass isdigit() if not (text.isascii() and text.isdigit()): return None try: value = int(text) except ValueError: # Python 3.11+ raises ValueError above 4,300 digits to block quadratic int-conversion DoS return None if value <= 0: return None return value class NotesAPI: """In-memory CRUD API for text notes, decoupled from any specific web server. POST /items body: text/plain -> 201 {"message": "created", "id": n} GET /items/{id} -> 200 {"id": n, "content": "..."} PUT /items/{id} body: text/plain -> 200 {"message": "updated", "id": n} DELETE /items/{id} -> 200 {"message": "deleted", "id": n} Errors -> {"message": "..."} with status 400, 404, 405, 413, or 415. """ def __init__(self, max_bytes: int = MAX_CONTENT_BYTES) -> None: self.max_bytes = max_bytes # _items: maps integer note id -> stored raw note string, e.g. {1: "inspect track 4"} self._items: Dict[int, str] = {} # _next_id: monotonically increasing ID counter; never decremented after DELETE self._next_id = 1 # _lock: guards _items and _next_id so concurrent requests never share an ID self._lock = threading.Lock() def handle(self, method: str, path: str, headers: Optional[Dict[str, str]] = None, body: bytes = b"") -> Response: """Normalize headers and URL path, route to the matching handler, and return a Response.""" # Phase 1: normalize header names to lowercase because HTTP header names are case-insensitive lower_headers: Dict[str, str] = {} for name, value in (headers or {}).items(): lower_headers[name.lower()] = value method_upper = method.upper() # Drop any query string (e.g. '?verbose=1') and trim leading/trailing slashes before splitting path_without_query = path.split("?", 1)[0] segments = path_without_query.strip("/").split("/") # Phase 2: collection route /items (supports POST only) if segments == ["items"]: if method_upper == "POST": return self._create(lower_headers, body) return error(405, "method not allowed", {"Allow": "POST"}) # Phase 3: single-item route /items/{id} (supports GET, PUT, DELETE) if len(segments) == 2 and segments[0] == "items": if method_upper not in ("GET", "PUT", "DELETE"): return error(405, "method not allowed", {"Allow": "GET, PUT, DELETE"}) item_id = parse_id(segments[1]) if item_id is None: return error(400, "id must be a positive integer") if method_upper == "GET": return self._read(item_id) if method_upper == "PUT": return self._update(item_id, lower_headers, body) return self._delete(item_id) # Phase 4: any other URL path does not exist return error(404, "route not found") def _text_body(self, headers: Dict[str, str], body: bytes) -> Tuple[Optional[str], Optional[Response]]: """Validate a text/plain request body; return (decoded_text, None) or (None, error_response).""" media_type, params = parse_media_type(headers.get("content-type")) if media_type != "text/plain": return None, error(415, "Content-Type must be text/plain") charset = params.get("charset", "utf-8") if charset not in ACCEPTED_CHARSETS: return None, error(415, "charset must be utf-8") # Check raw byte length (<= is inclusive) before decoding so oversized bodies fail fast if len(body) > self.max_bytes: return None, error(413, f"content must be at most {self.max_bytes} bytes") # Enforce 7-bit decoding if client explicitly declared us-ascii, otherwise full UTF-8 encoding = "ascii" if charset == "us-ascii" else "utf-8" try: text = body.decode(encoding) except UnicodeDecodeError: return None, error(400, f"body must be valid {encoding.upper()} text") # Reject empty or whitespace-only notes, but preserve surrounding spaces on valid text if not text.strip(): return None, error(400, "content must not be empty") return text, None def _create(self, headers: Dict[str, str], body: bytes) -> Response: """Validate text body, assign a fresh ID under the lock, and return 201 Created.""" text, problem = self._text_body(headers, body) if problem is not None: return problem with self._lock: item_id = self._next_id self._next_id += 1 self._items[item_id] = text return json_response( 201, {"message": "created", "id": item_id}, {"Location": f"/items/{item_id}"}, ) def _read(self, item_id: int) -> Response: """Return 200 with the note content if present, or 404 if missing.""" with self._lock: text = self._items.get(item_id) if text is None: return error(404, "item not found") return json_response(200, {"id": item_id, "content": text}) def _update(self, item_id: int, headers: Dict[str, str], body: bytes) -> Response: """Validate body first, then replace existing item under the lock (404 if missing).""" text, problem = self._text_body(headers, body) if problem is not None: return problem with self._lock: if item_id not in self._items: return error(404, "item not found") self._items[item_id] = text return json_response(200, {"message": "updated", "id": item_id}) def _delete(self, item_id: int) -> Response: """Remove an existing item under the lock and return 200 JSON (404 if missing).""" with self._lock: if item_id not in self._items: return error(404, "item not found") del self._items[item_id] return json_response(200, {"message": "deleted", "id": item_id}) def serve(port: int = 8000) -> None: """Expose NotesAPI over HTTP on 127.0.0.1:port using Python's standard library.""" # Import inside serve() so importing this module in unit tests never touches sockets from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer api = NotesAPI() class Handler(BaseHTTPRequestHandler): def _dispatch(self) -> None: try: length = int(self.headers.get("Content-Length") or 0) except ValueError: length = -1 if length < 0: response = error(400, "invalid Content-Length") else: # Cap read at max_bytes + 1 so handle() sees 413 without buffering huge uploads read_limit = min(length, api.max_bytes + 1) body = self.rfile.read(read_limit) if length > read_limit: self.close_connection = True response = api.handle(self.command, self.path, dict(self.headers), body) payload_bytes = json.dumps(response.body).encode("utf-8") self.send_response(response.status) for name, value in response.headers.items(): self.send_header(name, value) self.send_header("Content-Length", str(len(payload_bytes))) self.end_headers() self.wfile.write(payload_bytes) do_GET = _dispatch do_POST = _dispatch do_PUT = _dispatch do_DELETE = _dispatch do_PATCH = _dispatch ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever() if __name__ == "__main__": serve()✅ Submit now — all tests should pass.
Intuition & how it works
Think of a REST CRUD (Create, Read, Update, Delete) API like a post-office service window with a strict intake checklist: before touching the filing cabinet behind the counter, the clerk checks the envelope label (Content-Type: text/plain), weighs the parcel (max_bytes), verifies the box number (id), and always hands back a standardized JSON receipt (Content-Type: application/json) paired with an accurate HTTP status code. Putting all of that routing and validation inside a pure in-memory method (NotesAPI.handle) while keeping the TCP socket server (serve) as a thin outer wrapper also unlocks black-box testing — verifying behavior strictly from the public specification without inspecting internal source code.
A naive implementation tangles socket-handling with dictionary lookups, checks headers["Content-Type"] == "text/plain" literally, and converts path IDs with an unguarded int(segment). That approach breaks when real clients send content-type: Text/Plain; charset=UTF-8, crashes with KeyError or ValueError (returning raw HTML or a dropped connection instead of JSON) on missing headers or 5,000-digit IDs, and forces unit tests to bind network ports. Validating headers, byte lengths, encodings, and IDs explicitly inside handle makes every edge case deterministic and testable in microseconds.
Walk through five calls on a fresh NotesAPI():
1. POST /items with Content-Type: text/plain and b"inspect track 4" passes media-type, byte-limit, UTF-8, and non-empty checks, stores {1: "inspect track 4"}, and returns 201 with {"message": "created", "id": 1} plus Location: /items/1.
2. PUT /items/1 with Content-Type: application/json fails media-type validation first, returning 415 while leaving {1: "inspect track 4"} completely untouched.
3. PUT /items/1 with Content-Type: text/plain and b"track 4 cleared" replaces the stored value and returns 200 with {"message": "updated", "id": 1}.
4. DELETE /items/1 removes key 1 and returns 200 with {"message": "deleted", "id": 1}.
5. A second POST /items with b"check signal 9" increments _next_id to 2 (201, {"message": "created", "id": 2}), never reusing deleted ID 1.
Complexity
- Time: O(h + p + b) per request — which is O(1) for short headers/paths plus O(b) for a request body of
bbytes. Normalizinghheaders and splitting a URL path of lengthpscans each character once,body.decode(...)andtext.strip()scan at mostb <= max_bytesbytes once, and reading/writingself._items[item_id]is an O(1) average-time hash-map lookup. - Space: O(total stored note text) for the store, plus O(max_bytes) per active request. The dictionary
_itemsholds only live notes (deleted notes are removed immediately), andserve()caps socket reads atmax_bytes + 1bytes so a single oversized request cannot allocate unbounded memory. - Concurrency:
self._lockwraps only the O(1) dictionary and ID-counter lines (never body decoding or JSON serialization), so concurrent threads get strictly unique IDs with minimal lock contention.
Edge cases
- Case-insensitive
Content-Typeandcharsetparameters: missing header ->415;Text/Plain; charset="UTF-8"->201;text/plain; charset=latin-1->415;text/plain; charset=us-asciiaccepts 7-bit ASCII bytes (b"hello") and rejects non-ASCII bytes ("gate Δ".encode("utf-8")) with400;application/json->415. - Byte-exact size boundary: with
max_bytes = 8,"gate Δ".encode("utf-8")(6 characters,7UTF-8 bytes) succeeds with201, whileb"123456789"(9bytes) returns413without modifying existing text. - Empty, whitespace-only, and malformed UTF-8 bodies:
b"",b" \n\t", and invalid UTF-8b"\xff\xfe"return400, and a rejectedPUTpreserves the previously stored note text. - Tricky path IDs:
"abc","0","-1","1.5","1e3", Unicode superscript"²", and"9" * 5000(exceeding Python 3.11's 4,300-digitint()conversion limit) all return400cleanly. - Missing vs wrong-method routes:
/notesand/items/1/extrareturn404, whereasGET /itemsreturns405withAllow: POSTandPATCH /items/1returns405withAllow: GET, PUT, DELETE. - Black-box testing edge cases (Task 2): test equivalence classes, exact on/off boundary pairs (
0vs-1,max_bytesvsmax_bytes + 1), state preservation after errors, order-independent properties when the spec allows multiple valid answers, and randomized differential testing (comparing outputs against a simple reference model).
Common mistakes
- Exact string matching on
Content-Type: checkingheaders["Content-Type"] == "text/plain"crashes withKeyErrorwhen the header is missing or lowercase (content-type), and wrongly rejects standardtext/plain; charset=utf-8requests. - Letting web frameworks parse JSON or render HTML error pages by default: frameworks like Flask or FastAPI expect JSON models or return HTML on default
404/405routes unless you explicitly read raw body bytes and register JSON error handlers. - Returning
204 No Contentwith a JSON body: HTTP204responses are forbidden from carrying a message body; return200 OKwhen the contract requires JSON ({"message": "deleted", "id": 1}). - Computing
next_id = len(items) + 1ormax(items) + 1: after deleting an item, both formulas reuse old IDs or collide with existing keys! Always use a separate monotonically increasing counter. - Measuring character length (
len(text)) instead of byte length (len(body)), or reading the entireContent-Lengthbefore checkingmax_bytes: multi-byte UTF-8 characters slip past character limits, and unbounded socket reads invite out-of-memory crashes. - Over-specifying black-box tests: asserting one hardcoded list order or exact error wording when the specification only guarantees a mathematical property (like sum and max-minus-min spread) causes valid implementations to fail falsely.
Alternative approaches
- ASGI / WSGI web framework (
FastAPIorFlask) aroundNotesAPI: in production, Gunicorn/Uvicorn + FastAPI/Flask handles HTTP/1.1 keep-alive, timeouts, and TLS, while delegating business rules to the same framework-freeNotesAPIcore so unit tests remain instant. - SQLite or PostgreSQL storage: replacing
_itemsand_lockwith a table usingINTEGER PRIMARY KEY AUTOINCREMENT(SQLite) orGENERATED ALWAYS AS IDENTITY(PostgreSQL) persists notes across restarts and guarantees non-reused IDs via ACID transactions.
Follow-up questions
- How can you prevent concurrent editors from silently overwriting each other's changes on PUT /items/{id}? Use optimistic concurrency control (detecting write conflicts via version tags instead of holding database locks while a human types): return a version header such as
ETag: "v3"onGET /items/1, and requireIf-Match: "v3"onPUT /items/1. If another client already updated the note to"v4", reject the stale write with412 Precondition Failedso the client can fetch the latest text and merge changes safely. - How would you make POST /items safe to retry when a network timeout hides the original 201 response? Unlike
PUT,POSTis not naturally idempotent (an operation is idempotent when repeating it has the exact same effect as running it once), so a blind retry creates a duplicate note. Have clients send a uniqueIdempotency-Key: <uuid>header per logical create action; the server caches(idempotency_key -> Response)for a window like 24 hours and replays the original201response if the same key arrives again. - How should you design pagination on GET /items so deletions do not cause skipped or duplicate records? Support cursor pagination (fetching pages relative to the last seen item ID rather than a row-count offset), such as
GET /items?after=40&limit=20returning{"items": [...], "next_cursor": 63}. UnlikeOFFSET 20, cursor pagination by monotonically increasingidnever skips or duplicates items when earlier notes are deleted between page loads; validate1 <= limit <= 100and return400on out-of-range parameters.
Follow-up questions
- How can you prevent concurrent editors from silently overwriting each other's changes on PUT /items/{id}?
- How would you make POST /items safe to retry when a network timeout hides the original 201 response?
- How should you design pagination on GET /items so deletions do not cause skipped or duplicate records?
Similar questions
- Railcar Pricing Endpoint Service and Resilient High-Load Architecture
- Optimal Train Dispatch Under Yard Limits
- Minimum Removals for Pairwise Bridge Load
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination