Build a Plain-Text Notes REST API and Black-Box Test Plan
Data Structure DesignModel answerLast updated
Design a small CRUD HTTP service that accepts raw text bodies but replies in JSON, then explain how to test an unseen function from its specification alone.
This exercise has two parts.
Part 1: A plain-text CRUD service
Build a small HTTP service that manages a collection of short text entries (call them notes). Clients send raw text when writing, but every response from the server must be JSON.
Expose these routes:
POST /itemswithContent-Type: text/plaincreates a new note from the request body.GET /items/{id}returns the note with that id.PUT /items/{id}withContent-Type: text/plainreplaces the note's text.DELETE /items/{id}removes the note.
Example response shapes:
- Success:
{ "message": "created", "id": 1 } - Failure:
{ "message": "item not found" }
Your service should:
- Choose sensible HTTP status codes for each outcome.
- Handle missing notes, invalid input, and unsupported media types.
- Return JSON even for errors that the web framework would normally produce itself (unknown route, wrong method, oversized body).
Part 2: Testing without the source
You are given only the written specification of a function, not its implementation. Describe which behaviors you would test and how you would organize the tests so they give high confidence in correctness.
What to deliver
- A short description of the API contract (routes, status codes, validation order).
- Working code for the service in a language and framework of your choice.
- A systematic test strategy for Part 2, optionally applied to your own API.
Hints
Hint 1
Decide a fixed order for validating write requests: check the media type first, then whether the body is decodable and non-empty, and only then whether the target id exists. Write that order down and test it.
Hint 2
Compare the parsed media type, not the raw header string, so that `text/plain; charset=utf-8` is accepted. Also remember that framework-generated 404, 405 and 413 pages are usually HTML unless you register JSON error handlers.
Hint 3
For black-box testing, derive cases from the spec using equivalence classes, boundary values, documented error paths and invariants (round-trip, idempotence, no input mutation). Do not assert behavior the spec leaves undefined.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: The API
Contract
| Request | Success | Failures |
|---|---|---|
POST /items (text/plain) | 201 with {"message":"created","id":N} and a Location header | 415 wrong media type, 400 empty or non-UTF-8 body, 413 body too large |
GET /items/{id} | 200 with {"id":N,"content":"..."} | 404 |
PUT /items/{id} (text/plain) | 200 with {"message":"updated","id":N} | 415, 400, 404 |
DELETE /items/{id} | 200 with {"message":"deleted","id":N} | 404 |
| Unknown route or method | n/a | JSON 404 or 405 |
Design decisions worth stating out loud:
- DELETE returns 200 with a body, not 204. A 204 cannot carry a body, and the requirement is that every response is JSON. Returning 204 is also acceptable if you state that tradeoff.
- Validation order for writes: media type (415), then decoding and content (400), then existence (404). Problems with the shape of the request do not depend on server state, so they are checked first. Any consistent order is defensible, but it must be documented and tested.
- Ids come from a monotonically increasing counter and are never reused. A stale client holding a deleted id can never accidentally read a different note.
- Concurrency: a lock makes "check existence, then mutate" atomic when the server is threaded. In a real system this role is played by the database (unique keys, transactions).
- JSON everywhere: register error handlers for 404, 405 and 413 so framework defaults do not leak HTML.
Implementation (Flask)
import threading
from flask import Flask, request, jsonify, url_for
MAX_BYTES = 64 * 1024
def create_app():
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = MAX_BYTES
store, lock = {}, threading.Lock()
counter = {"next": 1}
def err(msg, code):
return jsonify(message=msg), code
def read_text():
if request.mimetype != "text/plain":
return None, err("unsupported media type; use text/plain", 415)
try:
text = request.get_data().decode("utf-8")
except UnicodeDecodeError:
return None, err("body must be valid UTF-8", 400)
if not text.strip():
return None, err("body must not be empty", 400)
return text, None
@app.post("/items")
def create():
text, e = read_text()
if e:
return e
with lock:
item_id = counter["next"]
counter["next"] += 1
store[item_id] = text
resp = jsonify(message="created", id=item_id)
resp.status_code = 201
resp.headers["Location"] = url_for("read", item_id=item_id)
return resp
@app.get("/items/<int:item_id>")
def read(item_id):
with lock:
if item_id not in store:
return err("item not found", 404)
return jsonify(id=item_id, content=store[item_id]), 200
@app.put("/items/<int:item_id>")
def update(item_id):
text, e = read_text()
if e:
return e
with lock:
if item_id not in store:
return err("item not found", 404)
store[item_id] = text
return jsonify(message="updated", id=item_id), 200
@app.delete("/items/<int:item_id>")
def delete(item_id):
with lock:
if store.pop(item_id, None) is None:
return err("item not found", 404)
return jsonify(message="deleted", id=item_id), 200
@app.errorhandler(404)
def not_found(_):
return err("not found", 404)
@app.errorhandler(405)
def bad_method(_):
return err("method not allowed", 405)
@app.errorhandler(413)
def too_large(_):
return err("payload too large", 413)
return app
Using an app factory (create_app) gives each test a fresh store, which keeps tests independent.
Complexity
- Time: each operation is an average O(1) dictionary access plus O(L) to decode a body of length L.
- Space: O(total stored text).
Edge cases to handle
Content-Typewith a charset parameter, different letter case, or missing entirely. Compare the parsed mimetype.- Empty body, whitespace-only body, invalid UTF-8 bytes.
- Unicode, emoji and multi-line text, stored verbatim.
- Non-integer id such as
/items/abc: the int route converter turns this into a clean 404 instead of a crash. PUTorDELETEon an already deleted id returns 404. A secondDELETEleaves server state unchanged, which is the sense in which it is idempotent.- Oversized body returns 413.
Common mistakes
- Returning 200 for every outcome.
- Returning HTML error pages for unknown routes or methods.
- Checking the raw header string, which rejects
text/plain; charset=utf-8. - Reusing ids after deletion.
- Checking existence and mutating without holding a lock.
Part 2: Testing a function you cannot see
Treat the specification as the oracle and design tests systematically.
- Equivalence partitioning. Split the inputs into classes the spec treats alike: typical valid input, each distinct kind of invalid input, empty input. Test at least one representative per class.
- Boundary values. Test at, just inside and just outside every limit: 0, 1 and max length, minimum and maximum numeric values, empty versus single-element collections.
- Error contract. For each documented failure, assert the exception type or status code, and the message where the spec fixes it.
- Properties and invariants. Relations that hold for all inputs: round-trip (
decode(encode(x)) == x), idempotence, order or length preservation, no mutation of arguments, determinism. Property-based tools such ashypothesisgenerate inputs and shrink failures to a minimal example. - Robustness inputs.
None, wrong types, Unicode, very large inputs, duplicates. Only assert what the spec defines. Where it is silent, record the ambiguity rather than guessing. - Structure. One behavior per test, Arrange-Act-Assert, descriptive names such as
test_put_missing_item_returns_404. Usepytest.mark.parametrizefor case tables and fixtures for isolation. Order the suites: happy path, boundaries, errors, properties.
Applying it to the API
import pytest
from app import create_app
@pytest.fixture
def client():
return create_app().test_client()
def post(client, body, ctype="text/plain"):
return client.post("/items", data=body, headers={"Content-Type": ctype})
def test_create_then_read(client):
r = post(client, "hello")
assert r.status_code == 201
item_id = r.get_json()["id"]
got = client.get(f"/items/{item_id}")
assert got.status_code == 200
assert got.get_json()["content"] == "hello"
@pytest.mark.parametrize("ctype", ["application/json", "text/html"])
def test_wrong_media_type_is_415(client, ctype):
assert post(client, "x", ctype).status_code == 415
@pytest.mark.parametrize("body", ["", " ", "\n\n"])
def test_blank_body_is_400(client, body):
assert post(client, body).status_code == 400
def test_charset_parameter_accepted(client):
assert post(client, "x", "text/plain; charset=utf-8").status_code == 201
def test_put_missing_item_returns_404(client):
r = client.put("/items/99", data="x", headers={"Content-Type": "text/plain"})
assert r.status_code == 404
def test_double_delete(client):
i = post(client, "x").get_json()["id"]
assert client.delete(f"/items/{i}").status_code == 200
assert client.delete(f"/items/{i}").status_code == 404
def test_ids_not_reused(client):
a = post(client, "a").get_json()["id"]
client.delete(f"/items/{a}")
b = post(client, "b").get_json()["id"]
assert b != a
def test_unknown_route_is_json(client):
r = client.get("/nope")
assert r.status_code == 404 and r.is_json
Each test uses only the public HTTP contract, so it would still pass if the implementation were rewritten in another framework. That is exactly the property you want from black-box tests.