Skip to content
Index Ai Academy
Phase 8 · FastAPI services

APIs with FastAPI

Typed routes, pydantic models, automatic validation and docs, tested with httpx.

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

What it covers7

First principles

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.

  1. Starting point

    POST JSON to a route with a Pydantic model

  2. What changes

    Validate required input fields

  3. Result

    The handler receives a validated model or the client receives a validation error

Compare all three steps
  1. Starting point

    POST JSON to a route with a Pydantic model

  2. What changes

    Validate required input fields

  3. Result

    The handler receives a validated model or the client receives a validation error

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

POST JSON to a route with a Pydantic model. Check that your implementation produces the result shown above.

Try it on a new case

How can you prove validation takes place before a database write?

Show worked reasoning

Send an input missing a required field, check the validation response, and verify that the database rows are unchanged.

Run, change, and build

Check this when debugging. Validating inputs by hand inside every endpoint instead of with types and models.

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. How can you prove validation takes place before a database write?

Why it matters

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.

What you'll be able to do

  • Build JSON API endpoints whose type hints convert and check every input
  • Describe request and response bodies with pydantic models and field constraints
  • Answer errors with HTTPException and share checks with dependencies
  • Test a FastAPI app with httpx, load a model once with lifespan, and call a model from a route with a cap and a timeout
Quick check
In FastAPI, a route has a parameter item_id: int. A request arrives for /items/abc. What happens?
  1. The server crashes with a TypeError
  2. FastAPI answers 422, since abc isn't an int
  3. Your function runs with item_id set to "abc"
  4. Your function runs with item_id set to 0
Show the answer

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.

The idea: the type hints are the checks

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.

Try it now

Pick each case in turn. The error cases leave early and the good one reaches the last gate, where the hash is dropped.

Quick check
Query values arrive as text. FastAPI converts each one with the type hint on the matching parameter, and answers 422 when that fails. This function does the same by hand. What does this print?
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))
  1. (200, {'a': 2, 'b': 3}) (200, {'a': 'abc', 'b': 3})
  2. (200, {'a': 2, 'b': 3}) (422, None)
  3. (422, None) (422, None)
  4. (200, {'a': '2', 'b': '3'}) (422, None)
Show the answer

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

Quick check
From the lesson on validating requests: in Python, True counts as a kind of int, so a check for numbers has to leave booleans out. What does this print?
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")])
  1. [True, True, False, True]
  2. [True, True, False, False]
  3. [True, True, True, False]
  4. [True, False, False, False]
Show the answer

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

In your own words
What does FastAPI do with the type hints on a route, and what is the response model for?

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

In Python: routes, bodies, errors and dependencies

An API from type hints

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.run needs 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.

Quick check
What does this print?
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())
  1. 3 200
  2. 21 422
  3. 3 422
  4. 3 404
Show the answer

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.

Bodies with pydantic models

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.

Quick check
A pydantic model has km: float = Field(gt=0). A request sends {"km": -3}. What does the endpoint's function receive?
  1. None, in place of the model
  2. A model whose km is still -3
  3. A model whose km was set to 0
  4. Nothing: FastAPI answers 422 first
Show the answer

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.

Drill

Constraints on a pydantic model

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"}))
In the lesson, your code is checked as you write it.

Errors and dependencies

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.

Quick check
A list endpoint gets its limit from a dependency with Query(10, ge=1, le=50). What does this print: the status and the limit for no limit, limit=5 and limit=80?
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())
  1. 200 10 200 5 200 50
  2. 200 10 200 5 422 -
  3. 200 10 200 5 404 -
  4. 200 - 200 5 422 -
Show the answer

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.

Quick check
The parameter x_api_key is declared with Header(). Which request header does FastAPI read into it?
  1. api-key
  2. x-api-key
  3. Authorization
  4. x_api_key, exactly as written
Show the answer

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.

Drill

Protect a route with a dependency

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)
In the lesson, your code is checked as you write it.

async def or def?

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

Quick check
An async def endpoint calls time.sleep(5), which doesn't await. What happens to the other requests during those 5 seconds?
  1. They are refused with a 503 error
  2. They run on other threads as usual
  3. They finish first, then it sleeps
  4. They wait: the event loop is blocked
Show the answer

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.

Documentation for free

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

Worked example: a response model that keeps secrets in

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

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

In your own words
What are dependencies for, and why does time.sleep in an async def endpoint hurt?

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

In AI and ML systems: load once, call with a cap

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.

Quick check
The model route is posted an empty ticket. Why is the model never called?
  1. The model refuses empty prompts and sends back an error instead
  2. The timeout ends the model call before it has a chance to start
  3. Its body fails validation, so FastAPI answers 422 before the route runs
  4. The token cap is already used up by an empty ticket
Show the answer

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.

Quick check
The app loads its model once at startup, in the lifespan, and three calls come in. How many times are the weights loaded? And if a route loaded them itself?
  1. Three times, and once
  2. Three times either way
  3. Once either way
  4. Once, and three times
Show the answer

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.

Where this shows up in an engineer's week

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.

In your own words
Why does a model belong in the lifespan function, and what two limits does a route that calls a model API need?

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

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

Try a quiz question

An endpoint is def search(q: str, limit: int = 10). A client calls /search?limit=5. What happens?

  1. 422: q has no default, so it's required
  2. It runs with q set to an empty string
  3. It runs with q set to None
  4. 404: the path doesn't match

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