Back
+30 XP
Concept

Gauntlet 06: Deterministic JSON Schema Validator

Dynamic API payloads must be strictly validated before touching application logic. A deterministic JSON Schema validator evaluates untrusted dictionaries against structural specifications: verifying data types, checking required keys, inspecting array items, and enforcing numerical boundary limits.

python
# Type checking and field recursion:
if "required" in schema:
    for key in schema["required"]:
        if key not in data:
            errors.append(f"Missing required field: {key}")

# Gauntlet 06: Deterministic JSON Schema Validator When building robust APIs, assuming incoming client JSON has the right types or keys is the leading cause of `KeyError`, `TypeError`, and unhandled 500 server crashes. 📜🛡️ The **JSON Schema** specification defines contracts for JSON documents: - **`type`**: `string`, `integer`, `number`, `boolean`, `array`, `object` - **`required`**: List of mandatory dictionary keys - **`properties`**: Recursive schemas for nested child keys - **`items`**: Schema for elements within a list - **`minimum` / `maximum`**: Numeric boundaries In this gauntlet build, you will implement a recursive schema validator from first principles without third-party dependencies. ```python # Recursive validation pattern: errors = [] if expected_type and not isinstance(data, py_type): errors.append(f"Expected {expected_type}") ``` ## Pop Quiz Why should API gateways validate JSON payloads against strict schemas before passing requests to internal business services? - [ ] It rejects malformed payloads and invalid types at the system boundary, preventing TypeErrors and data corruption deep within business logic. - [ ] Validating JSON schemas converts Python objects into hardware bytecode. - [ ] It forces client web browsers to execute cryptographic proof-of-work calculations. - [ ] Because JSON parsers drop payloads that have more than 3 nested dictionaries. ## Real-World Challenge Implement `validate_json_schema(data, schema, path: str = "") -> list[str]`. - Recursively validates `type` (distinguishing booleans from integers). - Enforces `required` fields on objects and validates child `properties`. - Validates list elements against `items` schema. - Enforces `minimum` and `maximum` bounds on numeric values. - Returns a list of human-readable error strings (empty list if completely valid). <details> <summary>Solution</summary> ```python def validate_json_schema(data, schema: dict, path: str = "") -> list[str]: errors = [] p_name = path or "root" # 1. Type validation type_map = { "string": str, "integer": int, "number": (int, float), "boolean": bool, "array": list, "object": dict } expected_type = schema.get("type") if expected_type: expected_py = type_map.get(expected_type) # Python bool is a subclass of int; explicitly disambiguate if expected_type in ("integer", "number") and isinstance(data, bool): errors.append(f"{p_name}: expected {expected_type}, received boolean") return errors if not isinstance(data, expected_py): errors.append(f"{p_name}: expected {expected_type}, received {type(data).__name__}") return errors # 2. Object validation if isinstance(data, dict): for req_field in schema.get("required", []): if req_field not in data: errors.append(f"{p_name}: missing required field '{req_field}'") for prop_name, prop_schema in schema.get("properties", {}).items(): if prop_name in data: child_path = f"{path}.{prop_name}" if path else prop_name errors.extend(validate_json_schema(data[prop_name], prop_schema, child_path)) # 3. Array validation if isinstance(data, list) and "items" in schema: item_schema = schema["items"] for idx, item_val in enumerate(data): child_path = f"{path}[{idx}]" errors.extend(validate_json_schema(item_val, item_schema, child_path)) # 4. Numeric constraints if isinstance(data, (int, float)) and not isinstance(data, bool): min_bound = schema.get("minimum") if min_bound is not None and data < min_bound: errors.append(f"{p_name}: value {data} is less than minimum {min_bound}") max_bound = schema.get("maximum") if max_bound is not None and data > max_bound: errors.append(f"{p_name}: value {data} exceeds maximum {max_bound}") return errors # Verification user_schema = { "type": "object", "required": ["uid", "username", "tags"], "properties": { "uid": {"type": "integer", "minimum": 1}, "username": {"type": "string"}, "tags": {"type": "array", "items": {"type": "string"}} } } # 1. Valid instance valid_payload = {"uid": 42, "username": "sir", "tags": ["admin", "dev"]} assert validate_json_schema(valid_payload, user_schema) == [] # 2. Invalid instance: missing field, negative int, wrong list type invalid_payload = {"uid": -5, "tags": [123, 456]} errs = validate_json_schema(invalid_payload, user_schema) assert len(errs) >= 3 assert any("missing required field 'username'" in e for e in errs) assert any("less than minimum" in e for e in errs) assert any("tags[0]: expected string" in e for e in errs) ``` </details>