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:

  1. In-memory plain-text CRUD service (NotesAPI): implement a framework-independent HTTP request router NotesAPI(max_bytes=10_000) whose handle(method, path, headers=None, body=b"") -> Response method 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.
  2. 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 — Requires Content-Type: text/plain (matched case-insensitively on both header name and media type; an optional charset parameter is permitted only if utf-8, utf8, or us-ascii, case-insensitive and optionally quoted). Validates len(body) <= max_bytes, decodes bytes (ascii when charset=us-ascii, otherwise utf-8), rejects empty or whitespace-only strings (while preserving leading/trailing whitespace on non-empty text), assigns a monotonically increasing integer ID starting at 1, and returns 201 with {"message": "created", "id": n} plus header "Location": f"/items/{n}".
  • GET /items/{id} — Returns 200 with {"id": n, "content": "..."} when item n exists, or 404 with {"message": "item not found"}.
  • PUT /items/{id} — Validates Content-Type, charset, byte size, decoding, and non-empty text first; if item n exists, replaces its content and returns 200 with {"message": "updated", "id": n}, otherwise returns 404 with {"message": "item not found"}. Failed PUT calls must leave existing stored text untouched.
  • DELETE /items/{id} — Deletes item n and returns 200 with {"message": "deleted", "id": n}, or 404 with {"message": "item not found"} if absent. Deleted IDs are never reused by later POST requests.

Routing, Validation & Concurrency Rules

  • Strip query strings (e.g., ?detail=1) and normalize leading/trailing slashes before matching routes.
  • Any path other than /items or /items/{id} returns 404 ({"message": "..."}).
  • Unsupported HTTP verbs on /items return 405 with header "Allow": "POST"; unsupported verbs on /items/{id} return 405 with "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 return 400.
  • On POST and PUT, missing or non-text/plain media types or unsupported charset values return 415; len(body) > max_bytes returns 413; invalid byte sequences for the active encoding or empty/whitespace-only text return 400.
  • Concurrent calls to handle from 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 (default 10_000 bytes; enforced on raw UTF-8/ASCII byte length, inclusive).
  • method is an ASCII HTTP verb string (matched case-insensitively).
  • headers is None or a Dict[str, str] with arbitrary header-name casing.
  • Every response body must be JSON-serializable and paired with "Content-Type": "application/json".

Step-by-step walkthrough

  1. Understand both tasks and lock down the API contract

    This question pairs two foundational backend skills:

    1. 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).
    2. 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 OK instead of 204 No Content on DELETE: HTTP 204 forbids a response body, whereas the prompt requires JSON on all responses ({"message": "deleted", "id": 1}).
    • PUT updates existing items only (404 if missing): the server owns ID assignment (1, 2, 3, …), so allowing clients to invent /items/999 via PUT would collide with future server-assigned IDs.
    • IDs are never reused after deletion: if item 2 is deleted, the next created note gets ID 3, preventing stale links to /items/2 from silently displaying someone else's new note.
    • Validation order on PUT /items/{id}: check HTTP verb (405) -> ID syntax (400) -> Content-Type and body (415 / 413 / 400) -> item existence (404), rejecting malformed requests before touching storage.
  2. 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's http.server as 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(...) and error(...), 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)
    
  3. 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 check headers.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 any key=value parameters, then run five validation checks in _text_body from 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 with max_bytes = 8, "gate Δ" passes (7 <= 8) while b"123456789" (9 bytes) returns 413. Also notice step 4 decodes strict 7-bit "ascii" when the client explicitly declares charset=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, params
    
  4. Parse item IDs safely and route requests

    Before touching the dictionary of notes, handle normalizes header names to lowercase, strips any query string (?verbose=1), strips leading/trailing slashes (/items/ becomes ["items"]), and dispatches by path segments:

    • ["items"]: allows POST; any other method gets 405 Method Not Allowed with header Allow: POST.
    • ["items", raw_id]: allows GET, PUT, DELETE (else 405 with Allow: GET, PUT, DELETE), then validates raw_id via parse_id.
    • Anything else (such as /notes or /items/1/extra): returns 404.

    parse_id guards against three classic Python edge cases:

    1. Unicode digits: "²".isdigit() returns True in Python, so we check text.isascii() and text.isdigit().
    2. Huge digit strings: since Python 3.11, int("9" * 5000) raises ValueError (limit 4,300 digits) to block denial-of-service attacks; catching ValueError converts that crash into a clean 400 JSON error.
    3. Zero: "0" passes isdigit(), so we check value <= 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 value
    
  5. Implement thread-safe CRUD operations and the HTTP adapter

    When a threaded server handles two simultaneous POST /items requests, both threads could read self._next_id == 1 at the same instant and overwrite each other unless guarded by a threading.Lock. We hold self._lock only 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(), Handler reads at most api.max_bytes + 1 bytes from the socket stream: reading 1 extra byte is enough for api.handle(...) to see len(body) > max_bytes and return 413 without 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!)
    
  6. 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 if statements. 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 of people non-negative integers summing to total_cents whose max and min differ by at most 1, and raises ValueError if people < 1 or total_cents < 0.

    1. Equivalence partitioning (group inputs into classes governed by the same rule, picking one clear test per class):
      • Divides evenly (100 cents across 4 people -> [25, 25, 25, 25]).
      • Leaves a remainder (100 cents across 3 people -> sorted shares [33, 33, 34]).
      • Fewer cents than people (2 cents across 5 people -> sorted shares [0, 0, 0, 1, 1]).
    2. 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) vs max_bytes + 1 (413); id = "1" vs id = "0".
    3. Failure modes and state-preservation invariants:
      • Assert exact exception types (ValueError, not ZeroDivisionError when people = 0) or exact HTTP status codes (400 vs 404 vs 415).
      • For stateful systems like NotesAPI, assert that failed writes leave stored state untouched (for example, a 400 or 415 PUT /items/1 does not erase the existing note).
    4. 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!). Asserting split_bill(100, 3) == [34, 33, 33] would over-specify and fail a valid implementation. Assert len(res) == people, sum(res) == total_cents, min(res) >= 0, and max(res) - min(res) <= 1 (or compare sorted(res)).
      • Check metamorphic relations (how outputs must relate when inputs transform): adding people cents (total_cents + people) must increase every sorted share by exactly 1.
    5. Reference-model (differential) testing:
      • For stateful APIs, run hundreds of random (create, read, update, delete) sequences against both NotesAPI and a tiny 20-line plain-dict reference model, asserting identical status codes and JSON bodies at every step.
    6. 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, forgetting people == 0, or counting characters instead of UTF-8 bytes) and verify your suite catches every one.
    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)]
    
  7. 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 b bytes. Normalizing h headers and splitting a URL path of length p scans each character once, body.decode(...) and text.strip() scan at most b <= max_bytes bytes once, and reading/writing self._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 _items holds only live notes (deleted notes are removed immediately), and serve() caps socket reads at max_bytes + 1 bytes so a single oversized request cannot allocate unbounded memory.
  • Concurrency: self._lock wraps 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-Type and charset parameters: missing header -> 415; Text/Plain; charset="UTF-8" -> 201; text/plain; charset=latin-1 -> 415; text/plain; charset=us-ascii accepts 7-bit ASCII bytes (b"hello") and rejects non-ASCII bytes ("gate Δ".encode("utf-8")) with 400; application/json -> 415.
  • Byte-exact size boundary: with max_bytes = 8, "gate Δ".encode("utf-8") (6 characters, 7 UTF-8 bytes) succeeds with 201, while b"123456789" (9 bytes) returns 413 without modifying existing text.
  • Empty, whitespace-only, and malformed UTF-8 bodies: b"", b" \n\t", and invalid UTF-8 b"\xff\xfe" return 400, and a rejected PUT preserves 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-digit int() conversion limit) all return 400 cleanly.
  • Missing vs wrong-method routes: /notes and /items/1/extra return 404, whereas GET /items returns 405 with Allow: POST and PATCH /items/1 returns 405 with Allow: GET, PUT, DELETE.
  • Black-box testing edge cases (Task 2): test equivalence classes, exact on/off boundary pairs (0 vs -1, max_bytes vs max_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: checking headers["Content-Type"] == "text/plain" crashes with KeyError when the header is missing or lowercase (content-type), and wrongly rejects standard text/plain; charset=utf-8 requests.
  • 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/405 routes unless you explicitly read raw body bytes and register JSON error handlers.
  • Returning 204 No Content with a JSON body: HTTP 204 responses are forbidden from carrying a message body; return 200 OK when the contract requires JSON ({"message": "deleted", "id": 1}).
  • Computing next_id = len(items) + 1 or max(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 entire Content-Length before checking max_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 (FastAPI or Flask) around NotesAPI: in production, Gunicorn/Uvicorn + FastAPI/Flask handles HTTP/1.1 keep-alive, timeouts, and TLS, while delegating business rules to the same framework-free NotesAPI core so unit tests remain instant.
  • SQLite or PostgreSQL storage: replacing _items and _lock with a table using INTEGER PRIMARY KEY AUTOINCREMENT (SQLite) or GENERATED 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" on GET /items/1, and require If-Match: "v3" on PUT /items/1. If another client already updated the note to "v4", reject the stale write with 412 Precondition Failed so 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, POST is 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 unique Idempotency-Key: <uuid> header per logical create action; the server caches (idempotency_key -> Response) for a window like 24 hours and replays the original 201 response 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=20 returning {"items": [...], "next_cursor": 63}. Unlike OFFSET 20, cursor pagination by monotonically increasing id never skips or duplicates items when earlier notes are deleted between page loads; validate 1 <= limit <= 100 and return 400 on out-of-range parameters.

Follow-up questions

Similar questions

More Bnsf interview questions

All 4 Bnsf questions →