What must an API validate before request data hits business logic?
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.
- Rewrite
validate_order(data)to enforce strict types, finite positive numbers, allowlisted keys, and return all field errors together. - Which checks belong here at API entry versus deeper inside domain logic?
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)
- "BLOCK PYTHON BOOLEANS"
In Python,
boolsubclassesint, soisinstance(True, int)isTrue. Checktype(qty) is intinstead. - "REJECT NAN AND INF"
Check
0 < price < math.inf(ormath.isfinite(price) and price > 0), and rejectNaN/Infinityat JSON parse time too. - "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.
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)))
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 issue | Starter result | Fixed result |
|---|---|---|
"sku": " " | Passes | Rejected (sku must be non-empty) |
"qty": true | Passes (bool is int) | Rejected (qty must be int 1..100) |
"unit_price": NaN or -5 | Passes | Rejected (positive and finite) |
"role": "admin" | Silently kept | Rejected (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:
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. Becauseboolsubclassesint, JSONtruepasses as1andfalsepasses as0. - Trusting Python's default
json.loadsto rejectNaNorInfinity. 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
**payloadinto 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 withDecimal. - "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'Brienare 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 →