Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Check every request against a JSON Schema and say exactly what's wrong.
How early can a server tell that a request cannot be used?
Validate parsed input at the service boundary. A schema describes required fields and their constraints so a handler can report a problem before mutating data.
Receive {"rating": "five"}
Validate the required integer rating
Return a field-level validation error
Receive {"rating": "five"}
Validate the required integer rating
Return a field-level validation error
Given Receive {"rating": "five"} and Return a field-level validation error, write down the missing step that connects them.
Validate the required integer rating
Now take Validate the required integer rating and the result above. Write an input and an implementation that could produce this trace.
Receive {"rating": "five"}. Check that your implementation produces the result shown above.
The rating must be between 1 and 5. What feedback should a rating of 8 receive?
Point to rating and state the accepted range. The API can reject this request before adding a review.
Check this when debugging. Validating with scattered ifs instead of one schema.
Every request body is untrusted input, like a form anyone can fill in. Checking it by hand, with an if for each field, gets long and inconsistent, and it drifts out of date. A schema describes the valid shape once, and one validator enforces it everywhere. The same schema language, JSON Schema, describes Claude's tool inputs, MCP's inputSchema, structured outputs and OpenAPI documents. Learn it once and you can read all of them.
{"email": "...", "age": 30}. A request sends {"email": "ana", "age": "thirty"}. What should happen?Reject it with a 422 that lists both problems
A schema says what valid looks like; checking against it catches both bad fields at once and tells the client exactly what to fix. Bad data stopped at the door can't break anything further in.
This rests on Types and data modeling, where hints described data without checking it. A request comes from outside, so something has to check it at the door.
Think of a paper form at a bank. It has boxes, and each box has rules: "date of birth", "numbers only", "required". A schema is that form, written down for a computer.
JSON Schema is itself JSON. Here's one for creating a campaign:
{
"type": "object",
"required": ["name", "budget"],
"properties": {
"name": {"type": "string", "minLength": 1, "maxLength": 80},
"budget": {"type": "number", "minimum": 1},
"channel": {"type": "string", "enum": ["search", "social", "email"]},
"tags": {"type": "array", "items": {"type": "string"}, "maxItems": 10}
},
"additionalProperties": false
}
Read it as: "an object with a name (1 to 80 characters) and a budget (at least 1), optionally a channel from a fixed list and up to 10 string tags, and nothing else".
The keywords you'll use most:
| keyword | checks |
|---|---|
type | object, array, string, number, integer, boolean or null |
properties, required | which keys an object has, and which must be present |
additionalProperties: false | no keys beyond those listed |
enum | the value is one of a fixed list |
minimum, maximum | number limits |
minLength, maxLength, pattern | string length and a regular expression |
items, minItems, maxItems | each array item's schema, and the array's length |
additionalProperties: false catches typos. Without it, a client that sends "budjet" gets a silent success, while the budget it meant to set is ignored. That's what the keyword protects against: misspelled or unexpected keys being silently accepted and ignored.
from dataclasses import dataclass @dataclass class Campaign: name: str budget: int = 0 c = Campaign(name="Spring", budget="lots") print(c.budget, type(c.budget).__name__)
lots str
The class said int and accepted the word "lots" without complaint. Hints describe the data. Something still has to check it at the edge, where a request comes in from outside. That is the job of the schema and the validator in this lesson.
{"name": "Spring", "budget": 250, "tags": ["q2"]}
The others miss the required budget, have an empty name (minLength 1), or use a channel outside the enum.
A teacher marking a test doesn't stop at the first mistake and hand the paper back. They go through the whole thing and circle everything that's wrong. A validator does the same: it collects every error instead of stopping at the first, because a client fixing a form wants all the problems at once, not one per round trip. It walks the data and the schema together and, at each value, checks that value's rules, then steps into object properties and array items and does the same there. Each error records where it is, as a path from the root: $ is the root, .name is a key and [2] is a list position counting from 0, so $.items[2].qty is the qty of the third item. The picture runs one bad body through the checks.
Four problems, found in one pass.
Write a sentence or two, then compare it with a good answer in the lesson.
The validator is a function that calls itself. This one checks only required, so the idea stays visible: check here, then recurse into each nested object with a longer path.
A function that calls itself this way is recursive, as in [[p7-recursion]].
def check_required(data, schema, path="$"): errors = [] for key in schema.get("required", []): if key not in data: errors.append((f"{path}.{key}", "is required")) for key, sub in schema.get("properties", {}).items(): if key in data and isinstance(data[key], dict): errors += check_required(data[key], sub, f"{path}.{key}") return errors schema = {"required": ["name", "address"], "properties": {"address": {"required": ["city", "zip"]}}} print(check_required({"address": {"city": "Denver"}}, schema))
That's the whole pattern: check here, then recurse with a longer path.
def validate(body): errors = [] if not isinstance(body.get("name"), str): errors.append("$.name: must be a string") budget = body.get("budget") if type(budget) is not int or budget < 0: errors.append("$.budget: must be a whole number, 0 or more") return errors print( len(validate({"name": 7, "budget": -5})), validate({"name": "Spring", "budget": 250}), )
2 []
The bad body has two problems, and the validator reports both in one answer. It doesn't stop at the first. The client can then fix everything in a single round trip. A good body gives an empty list, which is how the handler knows it is safe to go on.
JSON has fewer types than Python, so the mapping needs care. In Python, True counts as a kind of int, so isinstance(True, int) is True. In JSON Schema, a boolean is not an integer or a number. So a validator that forgets this accepts {"qty": true} as a quantity of 1:
print(isinstance(True, int), True + True) def is_integer(v): return isinstance(v, int) and not isinstance(v, bool) print(is_integer(3), is_integer(True), is_integer(3.0))
Also, 3.0 is a float in Python, but JSON Schema's integer accepts any number with no fractional part. Real validators accept 3.0 as an integer. The exercise keeps to whole int values for simplicity.
Everything in a query string is text, so validation at the edge starts by converting. Write coerce(params, types): types maps names to "integer" or "boolean". Return (values, errors): integers from digit strings (an optional leading - allowed), booleans from "true"/"false", other names passed through unchanged, and an error ("$.NAME", "must be an integer") or ("$.NAME", "must be true or false") for values that don't convert.
def coerce(params, types): return dict(params), [] print( coerce( {"limit": "20", "active": "yes", "q": "rain"}, {"limit": "integer", "active": "boolean"}, ) )
{"items": [{...}, {"price": -1}]}?$.items[1].price
Start at the root $, the key items, position 1 (counting from 0), then the key price.
"Your form was rejected" is no help. "Box 3 needs a date, and box 7 must be one of these three options" is. A good validation response is a 4xx (often 422) listing every problem with its location:
{
"error": {
"type": "invalid_request_error",
"message": "2 problems with the request body",
"details": [
{"path": "$.budget", "message": "must be at least 1"},
{"path": "$.channel", "message": "must be one of search, social, email"}
]
}
}
AI agents calling your API (or tools you give a model) recover far better from errors like these. "must be one of search, social, email" tells the model exactly what to send next time. "Bad request" leaves it guessing.
A model was asked to create a campaign and sent arguments that are almost right. A flat checker finds every problem with its path, builds the error response the model gets back, and then passes the corrected call.
import json SCHEMA = { "type": "object", "required": ["name", "budget"], "properties": { "name": {"type": "string", "minLength": 1}, "budget": {"type": "number", "minimum": 1}, "channel": {"type": "string", "enum": ["search", "social", "email"]}, }, "additionalProperties": False, } TYPES = {"string": str, "number": (int, float)} def flat_errors(data, schema): """Check a flat object against the schema: every problem, with its path.""" errors = [] for key in schema["required"]: if key not in data: errors.append({"path": f"$.{key}", "message": "is required"}) for key, value in data.items(): rule = schema["properties"].get(key) if rule is None: errors.append({"path": f"$.{key}", "message": "is not allowed"}) continue if isinstance(value, bool) or not isinstance(value, TYPES[rule["type"]]): errors.append({"path": f"$.{key}", "message": f"must be a {rule['type']}"}) continue if "enum" in rule and value not in rule["enum"]: errors.append( { "path": f"$.{key}", "message": "must be one of " + ", ".join(rule["enum"]), } ) if "minimum" in rule and value < rule["minimum"]: errors.append( {"path": f"$.{key}", "message": f"must be at least {rule['minimum']}"} ) if "minLength" in rule and len(value) < rule["minLength"]: errors.append({"path": f"$.{key}", "message": "can't be empty"}) return errors call = {"name": "Spring sale", "budget": "250", "channel": "tv", "budjet": 250} errors = flat_errors(call, SCHEMA) print( json.dumps( {"error": {"message": f"{len(errors)} problems", "details": errors}}, indent=2 ) ) fixed = {"name": "Spring sale", "budget": 250, "channel": "social"} print(flat_errors(fixed, SCHEMA))
The model sent the budget as text, picked a channel the API doesn't have, and added a misspelled key. One pass finds all three, each with its path and a message that says what valid looks like, and the corrected call passes with no errors.
This is the loop tool use runs on: a model that gets "must be one of search, social, email" back can fix the call on its next turn, where "Bad request" would leave it guessing. The checker is flat on purpose, one level of keys; the exercise builds the full version, which walks into nested objects and arrays.
Validators report paths like $.items[1].price. Write messages(errors): turn each (path, message) tuple into "items[1].price: must be a number" (drop the leading $., or the $ alone for the root), sorted by path, one string per error.
ERRORS = [
("$.items[1].price", "must be a number"),
("$.email", "is required"),
("$", "must be an object"),
]
def messages(errors):
return [message for path, message in errors]
print(messages(ERRORS))
print(isinstance(True, int), type(True) is int)
True False
bool is a subclass of int, so isinstance says True, but its exact type is bool, so type(True) is int says False. A validator that wants a real integer must reject bools explicitly.
Write a sentence or two, then compare it with a good answer in the lesson.
A model's tool call is a request body written by a model, and models make the same mistakes a careless client does: a number sent as text, an option that does not exist, a misspelled key. Every tool you give a model comes with a schema, the same JSON Schema you just read, and your code must still check each call against it, because the model is not a validator. The loop that makes tool use work is the one you built: check, list every problem with its path and what valid looks like, send the list back, and the model fixes the call on its next turn. The same schema language describes structured outputs, MCP's inputSchema and OpenAPI request bodies.
The same bad call as the picture, checked by pydantic. extra="forbid" is additionalProperties: false. The loop prints each problem with its location, the list a model would be sent back.
from typing import Literal from pydantic import BaseModel, Field, ValidationError class CampaignIn(BaseModel, extra="forbid"): name: str = Field(min_length=1) budget: float = Field(ge=1) channel: Literal["search", "social", "email"] = "search" call = {"name": "", "budget": "250", "channel": "tv", "budjet": 250} try: CampaignIn.model_validate(call) except ValidationError as e: for problem in e.errors(): print(".".join(map(str, problem["loc"])), "|", problem["msg"]) schema = CampaignIn.model_json_schema() print(schema["properties"]["channel"]["enum"], schema["required"])
Pydantic collected every problem at once, each with its location. It accepted "250" for the budget because it converts text to a number by default, which is a choice: a stricter model would reject it. The last line is the JSON Schema generated from the same class, which is what you give a model as a tool's input_schema.
Three habits come from this lesson. Reject what you don't recognize. If you ignore an unknown field, a client who sends {"budjet": 500} gets a silent success while the budget they meant to set is never set; and if you pass the whole body to your update code, a client can send {"is_admin": true} and possibly set it. Naming the allowed fields closes both holes. Validate once, at the edge, and hand a clean object inward, so code further in can trust what it receives. Watch what an error repeats back: echoing a value is fine for a budget and not for a password or a token, so leave sensitive fields out of messages. Only jsonschema is missing from the academy's Python; pydantic runs here, and APIs with FastAPI uses it for every request body. Goes deeper in: Documenting APIs with OpenAPI turns schemas like these into tool definitions, and Structured output makes a model's reply follow one.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
What does "additionalProperties": false protect against?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write