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.
Typed routes, pydantic models, automatic validation and docs, tested with httpx.
How does FastAPI decide whether it can call a typed endpoint?
A request model converts and validates incoming data before your route body runs. The resulting schema is also available for clients through generated API documentation.
POST JSON to a route with a Pydantic model
Validate required input fields
The handler receives a validated model or the client receives a validation error
POST JSON to a route with a Pydantic model
Validate required input fields
The handler receives a validated model or the client receives a validation error
Given POST JSON to a route with a Pydantic model and The handler receives a validated model or the client receives a validation error, write down the missing step that connects them.
Validate required input fields
Now take Validate required input fields and the result above. Write an input and an implementation that could produce this trace.
POST JSON to a route with a Pydantic model. Check that your implementation produces the result shown above.
How can you prove validation takes place before a database write?
Send an input missing a required field, check the validation response, and verify that the database rows are unchanged.
Check this when debugging. Validating inputs by hand inside every endpoint instead of with types and models.
FastAPI is one of the most used Python web frameworks, and the usual choice for putting a model behind an API (Serving a model behind FastAPI does it). Its central idea is that the type hints you already write are enough: from limit: int it knows to read a number from the query string, convert it, reject "abc" with a clear error, and list it in the API's documentation. You built that machinery by hand in the validation lesson; here a framework does it for you, and you learn where its defaults need your judgment.
item_id: int. A request arrives for /items/abc. What happens?FastAPI answers 422, since abc isn't an int
FastAPI reads your type hints and validates the input before your code runs, sending back a clear 422 when it doesn't fit. The same hints also produce the API's documentation.
This rests on Validating requests with schemas, where you checked a body against a schema by hand. FastAPI reads the type hints you already write and builds those checks for you. A parameter's name says where it comes from: a name in the path, like {slug}, comes from the path; another simple parameter comes from the query string; a pydantic model comes from the JSON body. The request then passes a fixed list of gates, in order, and leaves at the first one it fails. The checks run before your function, so inside the function every value is already the right type. The last gate matters for safety: the response model fixes which fields leave, so a field you did not name, such as a password hash, is dropped.
Pick each case in turn. The error cases leave early and the good one reaches the last gate, where the hash is dropped.
def convert(params, hints): try: return 200, {name: hints[name](value) for name, value in params.items()} except ValueError: return 422, None hints = {"a": int, "b": int} print(convert({"a": "2", "b": "3"}, hints), convert({"a": "abc", "b": "3"}, hints))
(200, {'a': 2, 'b': 3}) (422, None)
"2" and "3" convert to numbers, so the endpoint would receive real ints. "abc" can't be an int, so the request is refused with 422 before the endpoint's code runs at all. In FastAPI, the type hints on your function are the conversion table.
def is_number(value): return isinstance(value, (int, float)) and not isinstance(value, bool) print([is_number(v) for v in (3, 2.5, True, "3")])
[True, True, False, False]
3 and 2.5 are numbers. True would pass a plain isinstance(value, int), so the check rules booleans out by name. The text "3" isn't a number until something converts it. pydantic, in the next section, builds careful checks like this from your type hints.
Write a sentence or two, then compare it with a good answer in the lesson.
A FastAPI app looks much like a Flask app, with one difference that matters: the endpoint's parameters say what the request must contain. A name that appears in the path, like {slug}, comes from the path; any other simple parameter comes from the query string. Return a dictionary or a list, and FastAPI sends it as JSON.
import asyncio import httpx from fastapi import FastAPI api = FastAPI() TRAILS = { "red-mesa": {"name": "Red Mesa ridge", "km": 11.0}, "fern-hollow": {"name": "Fern Hollow loop", "km": 6.0}, } @api.get("/trails/{slug}") def trail(slug: str): return TRAILS.get(slug, {}) @api.get("/trails") def search(min_km: float = 0, limit: int = 10): found = [t for t in TRAILS.values() if t["km"] >= min_km] return found[:limit] async def main(): transport = httpx.ASGITransport(app=api) async with httpx.AsyncClient(transport=transport, base_url="http://test") as client: for url in ["/trails/red-mesa", "/trails?min_km=8", "/trails?limit=abc"]: reply = await client.get(url) print(url, reply.status_code, reply.json()) asyncio.run(main())
min_km=8 arrived as text and reached the function as the float 8.0. limit=abc never reached the function at all: FastAPI answered 422 Unprocessable Content with a description of exactly which input was wrong and why.
To call the app, the cell uses httpx, an HTTP client like requests, with a transport that hands each request straight to the app instead of the network. In a normal project you'd use FastAPI's TestClient, which wraps the same thing but runs the app in a background thread, and browsers can't start threads.
Note:
asyncio.runneeds a current browser (one with WebAssembly JSPI, like recent Chrome, Edge and Safari). If a cell here stops with an error about asyncio, run it on your own computer or update the browser.
import asyncio, httpx from fastapi import FastAPI api = FastAPI() @api.get("/add") def add(a: int, b: int = 1): return a + b async def main(): async with httpx.AsyncClient( transport=httpx.ASGITransport(app=api), base_url="http://t" ) as c: print((await c.get("/add?a=2")).json(), (await c.get("/add?b=5")).status_code) asyncio.run(main())
3 422
a="2" becomes the int 2, and b defaults to 1, so 3. A parameter without a default is required: leaving out a gives 422.
A POST usually sends a JSON body. Describe its shape with a pydantic model: a class whose annotated fields say the type of each value, plus constraints with Field. Use the model as a parameter's type, and FastAPI reads the body, converts it and validates it, all before your function runs.
import asyncio from datetime import date import httpx from fastapi import FastAPI from pydantic import BaseModel, Field, field_validator TODAY = date(2025, 6, 30) class HikeIn(BaseModel): trail: str = Field(min_length=1, max_length=80) day: date km: float = Field(gt=0, le=100) @field_validator("day") @classmethod def not_in_future(cls, value): if value > TODAY: raise ValueError("can't be in the future") return value class HikeOut(HikeIn): id: int api = FastAPI() HIKES = {} @api.post("/hikes", status_code=201) def add_hike(hike: HikeIn) -> HikeOut: new = HikeOut(id=len(HIKES) + 1, **hike.model_dump()) HIKES[new.id] = new return new async def main(): async with httpx.AsyncClient( transport=httpx.ASGITransport(app=api), base_url="http://test" ) as client: good = await client.post( "/hikes", json={"trail": "Red Mesa", "day": "2025-06-14", "km": "11.5"} ) print(good.status_code, good.json()) bad = await client.post( "/hikes", json={"trail": "", "day": "2025-07-14", "km": -2} ) print(bad.status_code) for problem in bad.json()["detail"]: print(" ", problem["loc"], problem["msg"]) asyncio.run(main())
Every problem is reported at once, each with its location (["body", "km"]) and a message, which is far more useful to the developer calling your API than a bare "invalid request". status_code=201 makes a successful POST answer 201 Created.
Rules that Field can't express, like "not after today", go in a method marked @field_validator. It receives the already converted value (here a real date, not text), raises ValueError with a short message when the value breaks the rule, and returns the value otherwise. pydantic adds that message to the same list of problems, so the caller sees one consistent kind of error, whichever rule failed.
The return annotation -> HikeOut is the response model: FastAPI converts the result to that shape and sends only its fields. That's an important safety net. If a database row has a password_hash column and the response model doesn't, the hash can never leak into a reply, even if someone returns the whole row by mistake.
km: float = Field(gt=0). A request sends {"km": -3}. What does the endpoint's function receive?Nothing: FastAPI answers 422 first
The body is checked against the model before your function is called. A km of −3 breaks the gt=0 rule, so FastAPI answers 422 with the field's location and the reason, and the function never runs. Inside the function, a model that arrived is a model that passed.
Add constraints to HikeIn with Field: name needs at least 1 character and km must be greater than 0. Then make parse(data) return the model, or, if validation fails, a sorted list of the field names that failed (each error's loc[0]).
from pydantic import BaseModel, Field, ValidationError class HikeIn(BaseModel): name: str km: float def parse(data): return HikeIn(**data) print(parse({"name": "Eagle Peak", "km": "12.5"}))
When an endpoint finds a problem that validation can't, it raises HTTPException. FastAPI turns it into a JSON error reply with the status you choose:
from fastapi import HTTPException @api.get("/hikes/{hike_id}") def get_hike(hike_id: int) -> HikeOut: if hike_id not in HIKES: raise HTTPException(status_code=404, detail="Hike not found") return HIKES[hike_id]
Checks that many endpoints share, like "is there a valid API key?" or "read the page and limit", go in a dependency: a function whose parameters FastAPI fills from the request, just like an endpoint's. Depends(...) asks for its result:
from fastapi import Depends, Header, Query def require_key(x_api_key: str | None = Header(default=None)): if x_api_key != API_KEY: raise HTTPException(status_code=401, detail="Missing or wrong API key") def paging(limit: int = Query(10, ge=1, le=50), offset: int = Query(0, ge=0)): return {"limit": limit, "offset": offset} @api.delete("/hikes/{hike_id}", status_code=204, dependencies=[Depends(require_key)]) def delete_hike(hike_id: int): ... @api.get("/hikes") def list_hikes(page: dict = Depends(paging)): ...
Header() reads a request header (the parameter x_api_key matches the header x-api-key), and Query(10, ge=1, le=50) adds limits to a query parameter. Dependencies can depend on other dependencies, which is how real apps build "the current user" from "the token" from "the header", each piece tested on its own.
import asyncio import httpx from fastapi import Depends, FastAPI, Query api = FastAPI() def paging(limit: int = Query(10, ge=1, le=50)): return {"limit": limit} @api.get("/hikes") def list_hikes(page: dict = Depends(paging)): return page async def main(): transport = httpx.ASGITransport(app=api) async with httpx.AsyncClient(transport=transport, base_url="http://t") as client: for query in ("", "?limit=5", "?limit=80"): r = await client.get("/hikes" + query) print(r.status_code, r.json().get("limit", "-")) asyncio.run(main())
200 10 200 5 422 -
With no limit, the dependency's default of 10 is used. 5 is within 1 to 50. 80 breaks le=50, so FastAPI answers 422 before the endpoint runs, and the error body has no limit key.
x-api-key
FastAPI turns the underscores in a header parameter's name into hyphens, so x_api_key reads x-api-key. Header names are case-insensitive, so X-API-Key works too.
Add a dependency async def require_key(x_api_key: str | None = Header(default=None)) that raises HTTPException(status_code=401, detail="Invalid API key") unless the key is "trail-secret", and attach it to /stats with dependencies=[Depends(require_key)]. FastAPI reads the X-API-Key header into x_api_key for you. get(path, headers) calls the app the way this lesson does.
import asyncio import httpx from fastapi import Depends, FastAPI, Header, HTTPException api = FastAPI() @api.get("/stats") async def stats(): return {"hikes": 12} def get(path, headers=None): async def main(): async with httpx.AsyncClient( transport=httpx.ASGITransport(app=api), base_url="http://test" ) as client: return await client.get(path, headers=headers or {}) return asyncio.run(main()) print(get("/stats").status_code)
This rests on Concurrency and async, where one event loop ran many waiting tasks. FastAPI accepts both kinds of function. An async def endpoint runs on the event loop, so while it awaits something slow, such as an async call to another service, the server handles other requests. A plain def endpoint runs in a worker thread, so blocking code inside it does not freeze everyone else. Use async def when everything slow in the endpoint is awaited; otherwise use def, and never call blocking code from an async def endpoint. Compare these two endpoints. (Shown, not run: the academy's Python has no threads and its sleep is simulated, so it can't show the stall. Run it on your own computer to see the times.)
@api.get("/blocking") async def blocking(): time.sleep(0.3) # holds the event loop return {"ok": True} @api.get("/awaiting") async def awaiting(): await asyncio.sleep(0.3) # lets other requests run return {"ok": True}
Three requests at once to the blocking endpoint take about 3 × 0.3 = 0.9 s, since each sleep holds the loop. The awaiting endpoint takes about 0.3 s, since the three sleeps overlap. The picture below draws the blocking case. (A plain def endpoint runs in a thread on a real server; here it runs directly, and your code does not need to change.)
async def endpoint calls time.sleep(5), which doesn't await. What happens to the other requests during those 5 seconds?They wait: the event loop is blocked
An async def endpoint runs on the event loop, and the loop can only switch to another request at an await. A plain time.sleep holds the loop for the full 5 seconds, so every other request waits. Use await asyncio.sleep, or a plain def endpoint.
From the routes, parameters and models, FastAPI writes an OpenAPI description of the whole API, as Documenting APIs with OpenAPI builds by hand. api.openapi() returns it as a dictionary, and on a server the pages /docs and /redoc show it as interactive documentation.
from fastapi import FastAPI from pydantic import BaseModel api = FastAPI(title="Trail log") class HikeIn(BaseModel): trail: str km: float @api.post("/hikes", status_code=201) def add_hike(hike: HikeIn) -> HikeIn: return hike @api.get("/hikes/{hike_id}") def get_hike(hike_id: int, verbose: bool = False): return {"id": hike_id} paths = api.openapi()["paths"] for path, methods in paths.items(): for method, op in methods.items(): params = [p["name"] for p in op.get("parameters", [])] print(method.upper(), path, params, list(op["responses"]))
A sign-up endpoint receives a password, stores a hash, and replies with the account. The response model decides what leaves the server.
import asyncio, hashlib, secrets import httpx from fastapi import FastAPI, HTTPException from pydantic import BaseModel, Field class SignUp(BaseModel): email: str = Field(pattern=r"^[^@\s]+@[^@\s]+$") name: str = Field(min_length=1) password: str = Field(min_length=12) class Account(BaseModel): id: int email: str name: str api = FastAPI() ROWS = {} @api.post("/accounts", status_code=201) def sign_up(form: SignUp) -> Account: if any(row["email"] == form.email for row in ROWS.values()): raise HTTPException(status_code=409, detail="That email is already registered") salt = secrets.token_hex(8) row = {"id": len(ROWS) + 1, "email": form.email, "name": form.name, "salt": salt, "password_hash": hashlib.sha256((salt + form.password).encode()).hexdigest()} ROWS[row["id"]] = row return row # the whole row, by mistake: the response model filters it async def main(): async with httpx.AsyncClient( transport=httpx.ASGITransport(app=api), base_url="http://test" ) as client: body = { "email": "ada@example.com", "name": "Ada", "password": "a long trail passphrase", } first = await client.post("/accounts", json=body) print(first.status_code, first.json()) again = await client.post("/accounts", json=body) print(again.status_code, again.json()) asyncio.run(main())
The endpoint returns the whole database row, salt and hash included, but the reply contains only id, email and name, because the return annotation says the answer is an Account. A second sign-up with the same email gets 409 Conflict, a status for requests that clash with the current state. (The hash here is SHA-256 only to keep the example short; the login lesson explains why real apps use bcrypt.)
time.sleep in an async def endpoint hurt?Write a sentence or two, then compare it with a good answer in the lesson.
A model behind an API follows three rules that FastAPI makes easy. Load once at startup, answer many times: loading weights is slow, so it belongs in a lifespan function that runs when the server starts and again at shutdown, never inside a route. Call outside models with a cap and a timeout: a route that calls a model API sets max_tokens and a timeout, and turns a failure into a clean 502. Answer fast, work later: a slow job goes to a background task, with 202 Accepted. Serving a model behind FastAPI builds a full service from these.
serve(app) runs an ASGI app's lifespan startup once and keeps its state for every request, the way a server would. This loads a "model" once at startup, and the three calls reuse it.
from contextlib import asynccontextmanager import requests from devserver import serve from fastapi import FastAPI MODEL = {} @asynccontextmanager async def lifespan(app): MODEL["weights"] = [0.5, -1.0] # loaded once, at startup MODEL["loads"] = MODEL.get("loads", 0) + 1 yield MODEL.clear() # released at shutdown api = FastAPI(lifespan=lifespan) @api.get("/score") def score(x: float): w = MODEL["weights"] return {"score": w[0] * x + w[1], "loads": MODEL["loads"]} base = serve(api) for x in (1, 2, 3): print(requests.get(f"{base}/score", params={"x": x}).json())
Three calls, one load: loads stays 1. A route that loaded the weights itself would load them three times. Now a route that calls a model API, with a token cap and a timeout, and a clean error when the call fails:
import requests from devserver import serve from fastapi import FastAPI, HTTPException from pydantic import BaseModel, Field api = FastAPI() class Ticket(BaseModel): text: str = Field(min_length=1, max_length=2000) @api.post("/classify") def classify(ticket: Ticket): body = { "model": "claude-opus-5-5", "max_tokens": 50, "messages": [{"role": "user", "content": f"Label this ticket: {ticket.text}"}], } url = "https://api.anthropic.com/v1/messages" reply = requests.post(url, json=body, timeout=20) if reply.status_code != 200: raise HTTPException(status_code=502, detail="The model call failed") texts = [b["text"] for b in reply.json()["content"] if b["type"] == "text"] return {"label": texts[0][:40]} base = serve(api) r = requests.post(f"{base}/classify", json={"text": "My tent zip broke"}) print(r.status_code, list(r.json())) r = requests.post(f"{base}/classify", json={"text": ""}) print(r.status_code)
The empty ticket never reaches the model: the body gate answers 422 first, which also saves the cost of a call. A reply is read by block type, since a reply may start with a thinking block.
Its body fails validation, so FastAPI answers 422 before the route runs
The body's own rules reject it, so the route's code, and the model call in it, never run. That also saves the cost of a call that could only fail.
Once, and three times
The lifespan's startup runs once and keeps its state for every request, so loads stays 1. A route that loaded the weights itself would load them on every call.
Three things go wrong in a model-backed FastAPI service. A route that loads weights on every request, which makes each reply seconds slow; the fix is lifespan. A blocking call in an async def route, such as a sync model client, which stalls every other request; the fix is def or an async client. A model call with no cap and no timeout, which lets one long generation hold a worker and a bill; the fix is max_tokens, timeout and a 502 you chose. Goes deeper in: Streaming from the server streams the reply, Project: a FastAPI service with accounts adds a database and accounts, and One request through a serving stack: latency and cost covers what happens on the GPU.
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.
An endpoint is def search(q: str, limit: int = 10). A client calls /search?limit=5. What happens?
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