Skip to content
Index Ai Academy
Phase 8 · Building APIs

Validating requests with schemas

Check every request against a JSON Schema and say exactly what's wrong.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

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.

  1. Starting point

    Receive {"rating": "five"}

  2. What changes

    Validate the required integer rating

  3. Result

    Return a field-level validation error

Compare all three steps
  1. Starting point

    Receive {"rating": "five"}

  2. What changes

    Validate the required integer rating

  3. Result

    Return a field-level validation error

Complete and reverse the trace

Given Receive {"rating": "five"} and Return a field-level validation error, write down the missing step that connects them.

Compare with the worked step

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.

Check one starting point

Receive {"rating": "five"}. Check that your implementation produces the result shown above.

Try it on a new case

The rating must be between 1 and 5. What feedback should a rating of 8 receive?

Show worked reasoning

Point to rating and state the accepted range. The API can reject this request before adding a review.

Run, change, and build

Check this when debugging. Validating with scattered ifs instead of one schema.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. The rating must be between 1 and 5. What feedback should a rating of 8 receive?

Why it matters

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.

What you'll be able to do

  • Write a JSON Schema for a request body: types, required fields, limits and enums
  • Build a schema validator that reports every problem with its exact location
  • Avoid the classic type traps, such as True counting as an integer
  • Return validation errors that a person or an AI agent can act on
  • Validate a model's tool call with pydantic and read a tool's input schema
Quick check
An API expects {"email": "...", "age": 30}. A request sends {"email": "ana", "age": "thirty"}. What should happen?
  1. Reject it with a 422 that lists both problems
  2. Crash, so the developer notices the problem
  3. Fix it quietly: guess the age and add @mail.com
  4. Store it as it is, since both fields are present
Show the answer

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.

The idea: a schema, and one list of every problem

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.

A schema says what valid looks like

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:

keywordchecks
typeobject, array, string, number, integer, boolean or null
properties, requiredwhich keys an object has, and which must be present
additionalProperties: falseno keys beyond those listed
enumthe value is one of a fixed list
minimum, maximumnumber limits
minLength, maxLength, patternstring length and a regular expression
items, minItems, maxItemseach 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.

Quick check
From the lesson on types: a dataclass declares typed fields, and Python doesn't enforce the hints. What does this print?
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__)
  1. TypeError int
  2. lots str
  3. 0 int
  4. lots int
Show the answer

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.

Quick check
Under the schema above, which body is valid?
  1. {"name": "Spring", "budget": 250, "channel": "tv"}
  2. {"name": "Spring"}
  3. {"name": "", "budget": 250}
  4. {"name": "Spring", "budget": 250, "tags": ["q2"]}
Show the answer

{"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.

Try it now

Four problems, found in one pass.

In your own words
What does a schema say, and why does a validator report every problem at once?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: a validator you can step through

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.

The recursive check

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))
It runs right here in your browser, with nothing to install.

That's the whole pattern: check here, then recurse with a longer path.

Quick check
A validator goes through the whole body and lists every problem, with the path to each. What does this print: the number of problems in a bad body, and the list for a good one?
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}),
)
  1. 2 None
  2. 1 []
  3. 2 []
  4. 0 []
Show the answer

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.

The type trap

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.

Drill

Query parameters arrive as text

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"},
    )
)
In the lesson, your code is checked as you write it.
Quick check
What path describes the price of the second item in {"items": [{...}, {"price": -1}]}?
  1. $.price
  2. $.items[1].price
  3. items.price[1]
  4. $.items[2].price
Show the answer

$.items[1].price

Start at the root $, the key items, position 1 (counting from 0), then the key price.

Errors people and agents can act on

"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.

Worked example

Worked example: a model's tool call, checked

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))
In the lesson you can change this and run it.

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.

Drill

Errors a person can act on

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))
In the lesson, your code is checked as you write it.
Quick check
This is the type trap from the lesson. What does it print?
print(isinstance(True, int), type(True) is int)
  1. True False
  2. True True
  3. False False
  4. False True
Show the answer

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.

In your own words
What is the type trap with booleans, and what does a good validation response contain?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: a model's tool call is untrusted input

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.

Worked example

Pydantic checks a model's tool call

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"])
In the lesson you can change this and run it.

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.

Where this shows up in an engineer's week

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.

In your own words
Why must you still validate a model's tool call when the model was given the schema?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

What does "additionalProperties": false protect against?

  1. Misspelled or unexpected keys being silently accepted and ignored
  2. Missing required keys being silently filled with defaults
  3. Values of the wrong type being converted without a warning
  4. Arrays that are too long being cut down to the allowed length

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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