download

What must an API validate before request data hits business logic?

Backend~10 minReviewed 3 Dec 2026Free · No sign-in

Question

POST /v1/orders accepts a JSON object with sku (non-empty string), qty (integer 1 to 100), and unit_price (positive finite number). Unknown fields must be rejected.

The starter validate_order lets qty: True, unit_price: NaN, negative prices, blank SKUs, and extra keys like role: "admin" slip through. It also stops at the first error.

  1. Rewrite validate_order(data) to enforce strict types, finite positive numbers, allowlisted keys, and return all field errors together.
  2. Which checks belong here at API entry versus deeper inside domain logic?
"CODE · PYTHON"
def validate_order(data):
    if not isinstance(data.get("sku"), str):
        return ["sku invalid"]
    if not isinstance(data.get("qty"), int):
        return ["qty invalid"]
    if not isinstance(data.get("unit_price"), (int, float)):
        return ["unit_price invalid"]
    return []
Show hints (3)
  1. "BLOCK PYTHON BOOLEANS"

    In Python, bool subclasses int, so isinstance(True, int) is True. Check type(qty) is int instead.

  2. "REJECT NAN AND INF"

    Check 0 < price < math.inf (or math.isfinite(price) and price > 0), and reject NaN/Infinity at JSON parse time too.

  3. "ALLOWLIST REQUEST KEYS"

    Compute data.keys() - {"sku", "qty", "unit_price"} and collect every violation into one list instead of returning early.

Show checked explanation

Validate structure, exact types, ranges, finite numbers, and an explicit field allowlist at API entry, returning every error together in one 422 response. Block Python booleans with type(x) is int and reject NaN/Infinity during JSON parsing. Keep stateful checks like live inventory or account balance in domain logic.

"SOLUTION · PYTHON"
import math


def validate_order(data):
    if not isinstance(data, dict):
        return ["body must be an object"]
    extra = sorted(data.keys() - {"sku", "qty", "unit_price"})
    errs = [f"unknown field: {k}" for k in extra]
    sku, qty, price = data.get("sku"), data.get("qty"), data.get("unit_price")
    if not isinstance(sku, str) or not sku.strip():
        errs.append("sku must be non-empty")
    if type(qty) is not int or not 1 <= qty <= 100:
        errs.append("qty must be int 1..100")
    if type(price) not in (int, float) or not (0 < price < math.inf):
        errs.append("unit_price must be positive and finite")
    return errs


bad = {"sku": "", "qty": True, "unit_price": float("nan"), "role": "admin"}
print("\n".join(validate_order(bad)))
"OUTPUT"
unknown field: role
sku must be non-empty
qty must be int 1..100
unit_price must be positive and finite

Ran the starter and fixed validator on CPython 3.12.10 against valid orders, bool/NaN/Infinity/negative/unknown-field traps, and strict json.loads parsing. Checked by an editor other than the author.

Walkthrough

Untrusted client payloads break services in subtle ways when validation only checks loose types:

Input payload issueStarter resultFixed result
"sku": " "PassesRejected (sku must be non-empty)
"qty": truePasses (bool is int)Rejected (qty must be int 1..100)
"unit_price": NaN or -5PassesRejected (positive and finite)
"role": "admin"Silently keptRejected (unknown field: role)
Non-object body []Crashes (AttributeError)Rejected (body must be an object)

Watch Python's JSON parser. RFC 8259 forbids NaN, Infinity, and -Infinity in JSON, yet Python's json.loads accepts them by default. Reject them at parse time so non-finite floats never enter your app:

"PYTHON"
def reject_constant(token):
    raise ValueError(f"invalid JSON constant: {token}")

payload = json.loads(raw_body, parse_constant=reject_constant)

Return all field errors together. Failing on the first bad field forces a web or mobile caller through four separate round trips to fix four mistakes. Collect every syntactic error into one list and return 422 Unprocessable Content with field-level details. Keep 400 Bad Request for unparseable JSON syntax and 413 Content Too Large for oversized bodies.

Reject unknown fields on write endpoints. Allowing arbitrary extra keys hides client typos (disocunt) and enables mass-assignment bugs when payloads are unpacked straight into models. Use an explicit allowlist.

Split entry validation from domain rules. Entry validation runs statelessly with zero database queries: types, formats, ranges, lengths, and allowed keys. Domain rules need current database state inside a transaction: Does sku exist? Are 10 units in stock? Does this user have credit left?

Common mistakes

  • Using isinstance(qty, int) in Python. Because bool subclasses int, JSON true passes as 1 and false passes as 0.
  • Trusting Python's default json.loads to reject NaN or Infinity. They parse into floats and corrupt totals or break strict databases.
  • Stopping after the first invalid field. Callers have to resubmit repeatedly to uncover every bad input.
  • Mixing slow database lookups into basic schema checks, or letting unknown keys pass through **payload into ORM updates.

Follow-up questions

  • "Why store or send money as integer cents instead of a JSON float like 19.99?" Binary floating-point cannot represent many decimal fractions cleanly (0.1 + 0.2 != 0.3), causing penny drift across sums and taxes. Accept integer minor units (unit_price_cents) or fixed-scale decimal strings and parse with Decimal.
  • "Should inbound API validation reject unknown fields everywhere, or only on writes?" Reject unknown fields on strict write requests (POST, PUT, PATCH) to catch typos and stop mass assignment. On public webhooks or forward-compatible event consumers, ignore unknown fields while mapping only allowlisted keys into internal objects.
  • "Does strict input validation replace parameterized SQL queries or output escaping?" No. OWASP treats validation as defense in depth. Names like O'Brien are valid input, so you still need parameterized queries for SQL and context-aware encoding for HTML.

What a strong answer covers

Catches Python bool, NaN/Infinity, blank strings, negative values, and unknown keys at entry. Collects all errors in one pass, configures strict RFC 8259 JSON parsing, and separates stateless schema checks from stateful domain rules.

Open in interactive practice deck →

Original OfferVibe question. OWASP Input Validation Cheat Sheet · RFC 8259 JSON · Python json module · JSON Schema Object Reference.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.