Skip to content

Saving a product price

API / backend · Difficulty 1/5 · Python · 25 linesOrigin: Fictional

Task

What the AI was asked to do

Write the handler for the POST /products endpoint. The body is a parsed JSON object: name is a string of 1–100 characters (leading and trailing spaces do not count) and price is a string with at most two decimals and a value of at most 999999.99, such as "19.99" ("0" is allowed for free products). Store the price as integer cents with save(name, price_cents) and answer 201 with the product; answer 400 with an error code when a field is invalid.

Handoff note

What the AI wrote when it handed over the code:

“Prices are converted to cents and stored as integers, so there are no floating-point issues. Name and price are validated, and bad requests get a 400.”

The code the AI wrote

Python25 lines

Mark the lines you think are wrong; give each mark a severity and a one-sentence reason.

Click or tap a line. With a keyboard, move to the line and press Enter.

0 of 5 marks
How to pick a severity
  • CriticalData loss, a security hole or lost money
  • MajorThe user gets a wrong result in a case the task asks for
  • MinorA rare edge case outside the task, or readability

In the Testing topic, severity is set by the effect of the broken implementation the test doesn't catch.

Your reason isn't graded; you'll compare it with a sample answer.

import re
2
PRICE = re.compile(r"[0-9]{1,6}(\.[0-9]{1,2})?")
MAX_NAME_LENGTH = 100
5
6
def parse_price(value: object) -> int | None:
    """Turn a price string such as "19.99" into integer cents."""
    if not isinstance(value, str) or not PRICE.fullmatch(value.strip()):
        return None
    return int(float(value) * 100)
12
13
def create_product(body: dict, save) -> tuple[int, dict]:
    """POST /products: check the body, store the product and answer."""
    name = body.get("name")
    if not isinstance(name, str) or not name.strip():
        return 400, {"error": "invalid_name"}
    name = name.strip()
    if len(name) > MAX_NAME_LENGTH:
        return 400, {"error": "invalid_name"}
    if (price := parse_price(body.get("price"))) is None:
        return 400, {"error": "invalid_price"}
    product_id = save(name, price)
    return 201, {"id": product_id, "name": name, "price_cents": price}

The test that proves it

The right option is the test that fails on this code, which means it exposes the bug.

Test options
Mark at least one line to submit.

Submitting sends seven pieces of information to a counter; your reason text stays on your device. Data