Skip to content
Index Ai Academy
Phase 8 · FastAPI services

Project: a FastAPI service with accounts

A session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.

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

Where should a trip service confirm ownership before an update?

A signed token identifies the caller and each request works with its own database session. The update must apply only to a trip that the caller owns.

  1. Starting point

    Account A requests an update to trip T

  2. What changes

    Look up T using its ID and A's ownership

  3. Result

    Commit a matching change or return the documented denial

Compare all three steps
  1. Starting point

    Account A requests an update to trip T

  2. What changes

    Look up T using its ID and A's ownership

  3. Result

    Commit a matching change or return the documented denial

Complete and reverse the trace

Given Account A requests an update to trip T and Commit a matching change or return the documented denial, write down the missing step that connects them.

Compare with the worked step

Look up T using its ID and A's ownership

Now take Look up T using its ID and A's ownership and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Account A requests an update to trip T. Check that your implementation produces the result shown above.

Try it on a new case

How do you test an update using a valid token from the wrong account?

Show worked reasoning

Create the trip under A, attempt the update as B, check the denial, then read the trip as A and verify its original data.

Run, change, and build

Check this when debugging. Checking that a user is logged in and assuming that means they may see the record.

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 do you test an update using a valid token from the wrong account?

Why it matters

Most backend jobs are some version of this project: an API with a database behind it, accounts in front of it, and rules about who may see what. Each piece appeared on its own in earlier lessons (FastAPI routes, SQLAlchemy models, password hashing, signed tokens). This project wires them into one service for the trail club's trip planner, the way a real codebase does, and builds the habits that separate a demo from something you'd deploy: no secrets in the code, no passwords in responses, no one reading another member's trips, and tests that start from a clean database every time.

What you'll be able to do

  • Give every request its own database session with a dependency that always closes it
  • Sign members up with bcrypt and log them in with short-lived signed tokens
  • Find the caller with a get_current_user dependency, and only ever show them their own data
  • Test the whole service against a fresh in-memory database with dependency overrides
Quick check
Members keep private trip lists, and an admin can see all of them. Where does "members only see their own" live?
  1. In the database password, which only members know
  2. In the API documentation, as a note for client developers
  3. In each query, filtered by the current user unless they're an admin
  4. In the client app, which hides other members' trips
Show the answer

In each query, filtered by the current user unless they're an admin

The rule has to run on the server, in every query that touches trips, with an exception for admins. Docs and client apps can't enforce anything, because a request can come from anywhere.

The brief: a trip planner with accounts

This rests on Authentication and authorization, which built a signed token from scratch, and APIs with FastAPI, which introduced dependencies.

Members sign up, log in, and keep a list of planned trips that only they can see; a club admin can see everyone's.

method and pathwho may call itwhat it does
POST /signupanyonecreates a member; 409 if the email is taken
POST /tokenanyonechecks email and password, returns a signed token; 401 if wrong
GET /mea logged-in memberwho the token belongs to
POST /trips, GET /tripsa logged-in memberadd a trip, list your trips (an admin sees all)
GET /trips/{id}, DELETE /trips/{id}the trip's owner, or an adminone trip; 404 for anyone else

In a real repository each layer gets its own file: models.py (database tables), schemas.py (the shapes that come in and go out), security.py (passwords and tokens), deps.py (the dependencies below) and main.py (the routes). Here each cell builds on the one before, so run them in order.

Try it now

Every protected route runs this chain before its own code. Three gates answer 401 and the last answers 404.

In your own words
Which checks does a request pass before your route code runs, and why is a trip that isn't yours a 404?

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

Build it: sessions, tokens and the owner check

Each cell builds on the one before, so run them in order. First, the database session that every route asks for.

A database session per request

Every request should get its own database session, and that session must be closed when the request ends, even if the route raises an error. A FastAPI dependency written with yield does exactly this: the code before yield runs before the route, the route gets the yielded value, and the finally part runs afterward, always.

import asyncio
import httpx
from fastapi import Depends, FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import ForeignKey, String, create_engine, func, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
from sqlalchemy.pool import StaticPool

class Base(DeclarativeBase):
    pass

class Member(Base):
    __tablename__ = "members"
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(String, unique=True)
    password_hash: Mapped[bytes]
    role: Mapped[str] = mapped_column(default="member")

class Trip(Base):
    __tablename__ = "trips"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    day: Mapped[str]
    owner_id: Mapped[int] = mapped_column(ForeignKey("members.id"))

def make_sessions(url="sqlite://"):
    # StaticPool keeps one connection, so an in-memory database
    # lives as long as the engine
    engine = create_engine(
        url, connect_args={"check_same_thread": False}, poolclass=StaticPool
    )
    Base.metadata.create_all(engine)
    return sessionmaker(bind=engine)

SessionLocal = make_sessions()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

class MemberOut(BaseModel):
    id: int
    email: str
    role: str

app = FastAPI()

@app.get("/members/count")
def count_members(db: Session = Depends(get_db)):
    return {"members": db.scalar(select(func.count()).select_from(Member))}

async def call(method, url, **kw):
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test"
    ) as client:
        return await client.request(method, url, **kw)

print(asyncio.run(call("GET", "/members/count")).json())

A few details matter. sessionmaker(bind=engine) is a factory: each call makes a fresh Session, just like the ORM lesson's Session(engine), so get_db can make one per request. check_same_thread=False lets a SQLite connection be used from another thread, which real FastAPI needs because it runs plain def routes in a pool of threads. StaticPool keeps a single connection open, because an in-memory SQLite database ("sqlite://") exists only while its connection does; on a real server the URL would point at PostgreSQL and the default pool would do. The count route asks the database to count (func.count()) instead of loading every row. And MemberOut is the shape the API will return for a member: it has no password_hash, so even a route that returns the database row can't leak the hash, once it declares response_model=MemberOut.

Quick check
This drives a yield dependency by hand, the way FastAPI does. What does it print?
def get_db():
    print("open")
    try:
        yield "db"
    finally:
        print("close")

steps = get_db()
db = next(steps)
print("route uses", db)
next(steps, None)
  1. route uses db open close
  2. open close route uses db
  3. open route uses db
  4. open route uses db close
Show the answer

open route uses db close

next() runs the function up to yield, printing open and handing over the session. The route uses it. The second next() resumes after yield, so the finally block prints close; the function then ends, and next's default None stops it raising StopIteration.

FastAPI does the same with get_db: it runs the dependency up to yield, passes the session to the route, and resumes the function once the route is done, so the finally block closes the session. If the route raises an error, FastAPI throws that error into the dependency at the yield, and finally still runs. That's why the try/finally is there: without it, every failed request would leave a session open, and on a busy server those open sessions pile up until the connection pool runs dry and every new request waits.

Quick check
A route returns the Member row from the database and has no response_model. What does the client receive?
  1. A 500 error every time, since the row isn't a plain dict that can become JSON
  2. Every column FastAPI can serialize, including password_hash, unless a response model filters it
  3. Only the id and email, since FastAPI hides fields that look like hashes automatically
  4. Nothing: ORM rows can't be returned from a route without converting them first
Show the answer

Every column FastAPI can serialize, including password_hash, unless a response model filters it

FastAPI converts what you return. Declaring response_model=MemberOut makes the output shape explicit, so fields like password_hash never leave the server, whatever the route returns.

Quick check
From the lesson on FastAPI: with a response model, only the model's fields are sent. This does the same by hand for one row of the members table. What does this print?
row = {
    "id": 7,
    "email": "ana@example.com",
    "password_hash": "$2b$12$abc",
    "is_admin": False,
}
MEMBER_OUT = ["id", "email"]
print({field: row[field] for field in MEMBER_OUT})
  1. ['id', 'email']
  2. {'password_hash': '$2b$12$abc', 'is_admin': False}
  3. {'id': 7, 'email': 'ana@example.com', 'is_admin': False}
  4. {'id': 7, 'email': 'ana@example.com'}
Show the answer

{'id': 7, 'email': 'ana@example.com'}

The row holds four columns, and only the two that are named go out. The password hash stays on the server though the route returned the whole row. A response model is a list of what may leave, so a column added to the table later doesn't leak by accident.

Passwords and tokens

Signing up stores a bcrypt hash of the password, never the password itself, using a cost (the number of rounds) that makes each guess slow. Logging in checks the password with bcrypt.checkpw and hands back a token: the signed HS256 kind from the auth lesson, carrying the member's id (sub), role and an expiry about 30 minutes away.

The signing secret comes from the environment, not the source code. Code is shared, copied and committed; a secret written in it is a secret every reader of the repository has. The cell below falls back to a practice value only so it runs here.

import base64, hashlib, hmac, json, os, time
import bcrypt

SECRET = os.environ.get("TOKEN_SECRET", "practice-only-secret").encode()
ROUNDS = 4          # fast for the browser; real services use 12 or more

def hash_password(password):
    return bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=ROUNDS))

def check_password(password, hashed):
    return bcrypt.checkpw(password.encode(), hashed)

def b64(data):
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

def make_token(member_id, role, minutes=30, now=None):
    now = time.time() if now is None else now
    head = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
    body = b64(
        json.dumps(
            {"sub": str(member_id), "role": role, "exp": int(now + minutes * 60)}
        ).encode()
    )
    sig = b64(hmac.new(SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest())
    return f"{head}.{body}.{sig}"

def read_token(token, now=None):
    """The token's claims, or None if it's malformed, forged or expired."""
    now = time.time() if now is None else now
    try:
        head, body, sig = token.split(".")
        good = b64(hmac.new(SECRET, f"{head}.{body}".encode(), hashlib.sha256).digest())
        if not hmac.compare_digest(sig.encode(), good.encode()):
            return None
        claims = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
    except (ValueError, json.JSONDecodeError):
        return None
    return claims if claims.get("exp", 0) > now else None

h = hash_password("pine-gap-ridge")
print(check_password("pine-gap-ridge", h), check_password("pine-gap-rigde", h))
t = make_token(7, "member")
print(
    read_token(t)["sub"],
    read_token(t[:-2] + "xx"),
    read_token(make_token(7, "member", minutes=-1)),
)
It runs right here in your browser, with nothing to install.

The last line shows the three outcomes that matter: a good token gives its claims; a tampered signature and an expired token both give None. A route never has to know which went wrong: either way the answer is 401.

Compared with the auth lesson's checklist, two checks are left out on purpose. This service never reads alg from the token: it always verifies with HS256, so a forged header can't switch the algorithm. And one service issues and reads its own tokens, so there's no audience to check; add aud when several services share a secret, and use a maintained library such as PyJWT in production. One more habit: a failed login gets the same 401 whether the email is unknown or the password is wrong, so the login form can't be used to test who's a member. That isn't airtight (signup's 409 says an email is taken, and skipping bcrypt for an unknown email answers faster), which is why real services also limit how often these routes can be called.

Quick check
A failed login answers 401 whether the email is unknown or the password is wrong. Why give the same answer?
  1. Because 401 is the only status code a login may return
  2. So that the browser asks again for the password
  3. So the login form can't be used to find out who is a member
  4. Because the server can't tell those two cases apart
Show the answer

So the login form can't be used to find out who is a member

Different answers would let anyone test an email address against the form. One answer for both hides that, though not perfectly: signup's 409 and timing still leak a little, which is why real services also limit how often these routes can be called.

Quick check
The service always verifies tokens with HS256 and never reads the alg field from the token. What does that prevent?
  1. A token expiring before its 30 minutes are up
  2. A forged header switching the algorithm the check uses
  3. A tampered signature giving back the token's claims
  4. Two services sharing one signing secret
Show the answer

A forged header switching the algorithm the check uses

If the verifier believed the token's own header, an attacker could name a weaker algorithm, or none. Fixing HS256 in the code means the token can't choose how it is checked.

Drill

A permission table

Write can(role, action, owner_id, user_id): members may "read", "update" and "delete" only their own records (owner_id == user_id); admins may "read" any record and "delete" any, but "update" only their own. Unknown roles or actions get False.

def can(role, action, owner_id, user_id):
    return role == "admin" or owner_id == user_id


print(can("admin", "update", 7, 1), can("member", "read", 7, 7))
In the lesson, your code is checked as you write it.

Who is asking, and what may they see

get_current_user is the dependency every protected route lists. It turns a token into a member, or stops the request with 401 and the header WWW-Authenticate: Bearer, which tells clients which kind of credential to send. OAuth2PasswordBearer(tokenUrl="token") reads the token from the Authorization header, and records in the API's generated docs that these routes need one. One catch on a real server: the docs page's Authorize button sends username and password as form fields to tokenUrl, and this project's /token reads JSON, so the button gets a 422 and logs no one in. Test with your own requests, or have /token accept OAuth2PasswordRequestForm, FastAPI's form version, if you want the button to work.

Quick check
A request reaches a protected route with no token. What does get_current_user answer?
  1. 401, with WWW-Authenticate: Bearer
  2. 200, with an empty member
  3. 403, since the caller isn't allowed
  4. 404, so the route seems not to exist
Show the answer

401, with WWW-Authenticate: Bearer

No token means no member, so the dependency stops the request with 401, and the header tells the client to send a bearer token. 404 is the answer for someone else's trip, which comes next.

Authorization is the next step, and the most common serious bug in real APIs is skipping it: a route that loads /trips/42 without checking that trip 42 belongs to the caller. Anyone logged in can then read anyone's data by counting through ids, a hole called an insecure direct object reference (IDOR). It's the same hole Authentication and authorization calls broken object-level authorization (BOLA). The fix is to filter by owner in the query itself, and to answer 404 rather than 403 for someone else's trip, so the API doesn't even confirm that the trip exists.

from fastapi.security import OAuth2PasswordBearer

oauth2 = OAuth2PasswordBearer(tokenUrl="token")


def get_current_user(
    token: str = Depends(oauth2), db: Session = Depends(get_db)
) -> Member:
    claims = read_token(token)
    member = db.get(Member, int(claims["sub"])) if claims else None
    if member is None:
        raise HTTPException(
            401, "Not logged in", headers={"WWW-Authenticate": "Bearer"}
        )
    return member


@app.get("/trips/{trip_id}")
def get_trip(
    trip_id: int, me: Member = Depends(get_current_user), db: Session = Depends(get_db)
):
    trip = db.scalar(select(Trip).where(Trip.id == trip_id, Trip.owner_id == me.id))
    if trip is None:
        raise HTTPException(404, "Trip not found")
    return trip

Notice that owner_id == me.id sits inside the query: it isn't an afterthought checked once the trip is loaded, so a later edit can't easily drop it.

Quick check
A member sees only their own trips, and an admin sees them all. A trip that isn't yours and a trip that doesn't exist get the same answer. What does this print?
TRIPS = {17: {"owner": "bo"}, 18: {"owner": "ana"}}

def get_trip(trip_id, user, is_admin=False):
    trip = TRIPS.get(trip_id)
    if trip is None or (trip["owner"] != user and not is_admin):
        return 404
    return 200

print(
    get_trip(17, "ana"),
    get_trip(18, "ana"),
    get_trip(17, "root", is_admin=True),
    get_trip(99, "ana"),
)
  1. 200 200 200 404
  2. 404 200 404 404
  3. 404 200 200 404
  4. 403 200 200 404
Show the answer

404 200 200 404

Ana gets a 404 for Bo's trip, the same as for trip 99, which doesn't exist. From the outside the two can't be told apart, so nobody learns which ids are real. Her own trip works, and an admin can read Bo's.

Quick check
Ana is logged in and requests GET /trips/17, which belongs to Bo. With the code above, what does she get, and why that status?
  1. 403: she's logged in but not allowed to see it, and saying so plainly is clearer for her
  2. 200 with Bo's trip, since she's logged in and the trip id she asked for is a real one
  3. 401: her token isn't valid for that trip, so she has to log in again as its owner
  4. 404: the query filters by owner, so for Ana trip 17 doesn't exist, and nobody learns it exists
Show the answer

404: the query filters by owner, so for Ana trip 17 doesn't exist, and nobody learns it exists

Her token is fine, so it isn't 401. Answering 403 would reveal that trip 17 exists; 404 treats someone else's trip exactly like a missing one, which leaks nothing.

Drill

Close the hole: only your own trips

The starter's trip routes check the token but not the owner, so any member can read or delete anyone's trip. Fix list_trips (a member sees only their own trips, an admin sees all) and delete_trip (404 unless the trip is the caller's; admins may delete any). The models, tokens and current_user are given; a tiny in-memory store stands in for the database so the fix is all you see.

from fastapi import Depends, FastAPI, Header, HTTPException

TRIPS = {
    1: {"name": "Fern Hollow loop", "owner": "ana"},
    2: {"name": "Red Mesa climb", "owner": "bo"},
    3: {"name": "Pine Gap walk", "owner": "ana"},
}
TOKENS = {
    "t-ana": {"user": "ana", "role": "member"},
    "t-bo": {"user": "bo", "role": "member"},
    "t-cy": {"user": "cy", "role": "admin"},
}

app = FastAPI()


def current_user(authorization: str = Header(default="")):
    user = TOKENS.get(authorization.removeprefix("Bearer "))
    if user is None:
        raise HTTPException(
            401, "Not logged in", headers={"WWW-Authenticate": "Bearer"}
        )
    return user


@app.get("/trips")
def list_trips(me: dict = Depends(current_user)):
    return [{"id": i, **t} for i, t in TRIPS.items()]


@app.delete("/trips/{trip_id}", status_code=204)
def delete_trip(trip_id: int, me: dict = Depends(current_user)):
    if trip_id not in TRIPS:
        raise HTTPException(404, "Trip not found")
    del TRIPS[trip_id]
In the lesson, your code is checked as you write it.
In your own words
How does a login become a protected request, and why does each request get its own database session?

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

Ship it: tests, usage and a deploy

A service that works on your laptop is not shipped. Three things stand between the two: tests that do not depend on each other, a record of who uses what, and a real deployment.

Tests that start clean

A test that depends on what an earlier test left in the database passes or fails depending on the order you run them in, the most frustrating kind of flaky test. FastAPI's app.dependency_overrides fixes this: map the real get_db to a replacement, and every route that asks for get_db gets the replacement instead. Give each test a brand-new in-memory database and nothing leaks between them:

def fresh_app():
    sessions = make_sessions()                     # a new, empty in-memory database
    def test_db():
        db = sessions()
        try:
            yield db
        finally:
            db.close()
    app.dependency_overrides[get_db] = test_db
    return app

The routes don't change at all: they still say Depends(get_db). That's the payoff of getting the session from a dependency instead of a global: the same seam lets tests swap the database, and lets production swap SQLite for PostgreSQL. Remember to clear the overrides afterward (app.dependency_overrides.clear()) if other tests use the same app.

Worked example

Worked example: two tests, one database or a fresh one each

Each "test" adds one member and reports the count. Run them against the app's own database, then again with an override that gives each one a brand-new database.

import asyncio
import httpx
from fastapi import Depends, FastAPI
from sqlalchemy import String, create_engine, func, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
from sqlalchemy.pool import StaticPool


class Base(DeclarativeBase):
    pass


class Member(Base):
    __tablename__ = "members"
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(String, unique=True)


def make_sessions():
    engine = create_engine(
        "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
    )
    Base.metadata.create_all(engine)
    return sessionmaker(bind=engine)


SessionLocal = make_sessions()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


app = FastAPI()


@app.post("/members/{email}", status_code=201)
def add_member(email: str, db: Session = Depends(get_db)):
    db.add(Member(email=email))
    db.commit()
    return {"members": db.scalar(select(func.count()).select_from(Member))}


async def call(url):
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test"
    ) as client:
        return (await client.post(url)).json()


def fresh_database():
    sessions = make_sessions()

    def test_db():
        db = sessions()
        try:
            yield db
        finally:
            db.close()

    app.dependency_overrides[get_db] = test_db


for name in ["first", "second"]:
    print(
        name, "test, shared database:", asyncio.run(call(f"/members/{name}@club.test"))
    )

for name in ["first", "second"]:
    fresh_database()
    print(
        name, "test, fresh database: ", asyncio.run(call(f"/members/{name}@club.test"))
    )
app.dependency_overrides.clear()
In the lesson you can change this and run it.

Against the shared database, the second test sees the first test's member and counts 2. Run the tests in the other order, or one alone, and the numbers change: that's how order-dependent, flaky tests are born.

With app.dependency_overrides[get_db] pointing at a new in-memory database before each test, both start empty and both count 1, whatever ran before. The route didn't change at all; it still says Depends(get_db). Clearing the overrides at the end puts the real database back for anything that runs next.

A usage table, the groundwork for model quotas

When this service one day calls a model for each member, you will need to know who spent what. The cheapest start is a table with a row per member per day, written as work happens, and a query that sums it. The cell builds the table in memory and finds who is over a daily budget of 1,000 tokens.

from sqlalchemy import create_engine, func, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column

class Base(DeclarativeBase):
    pass

class Usage(Base):
    __tablename__ = "usage"
    id: Mapped[int] = mapped_column(primary_key=True)
    member_id: Mapped[int]
    day: Mapped[str]
    tokens: Mapped[int]

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
with Session(engine) as db:
    db.add_all([
        Usage(member_id=1, day="2026-11-13", tokens=600),
        Usage(member_id=1, day="2026-11-13", tokens=500),
        Usage(member_id=2, day="2026-11-13", tokens=700),
    ])
    db.commit()
    for member in (1, 2):
        total = select(func.sum(Usage.tokens)).where(
            Usage.member_id == member, Usage.day == "2026-11-13"
        )
        used = db.scalar(total)
        print(member, used, "over" if used > 1000 else "ok")

Member 1 spent 1,100 of 1,000 and is over; member 2 spent 700. The query filters by member, the same owner filter as the trips route, so one member's usage can never be read as another's. Serving a model behind FastAPI puts a daily budget like this in front of a model.

Portfolio brief

Do it for real: deploy the trip planner

Put your FastAPI trip planner on the internet. Pick any host with a free or cheap tier that runs Python web apps (Railway, Render and Fly.io all do), deploy from your GitHub repository, and set the secrets there rather than in the code.

Paste the public address and your deploy notes into the starter, then ask the tutor to review your deployment against the rubric. A working URL is the strongest line a beginner's CV can have.

It must

  • Deploy from a GitHub repository, so a push redeploys it
  • Serve it over HTTPS at a public address
  • Set the token secret and the database address as environment variables on the host, not in the code
  • Add a /health route that answers 200 without touching the database
  • Write short deploy notes in the README: how to run it locally, how it's deployed, and its address

Go further

  • Use a managed Postgres instead of SQLite, and say what changed
  • Return the API's interactive docs at /docs and link them from the README
import re

URL = "https://trip-planner-yourname.up.railway.app"
NOTES = '''Deployed on Railway from GitHub (main branch).
Secrets: TOKEN_SECRET and DATABASE_URL are set in the Railway dashboard.
Health check: GET /health returns {"ok": true}.
'''


def check(url, notes):
    problems = []
    if not re.fullmatch(r"https://[A-Za-z0-9.-]+\.[A-Za-z]{2,}(/.*)?", url.strip()):
        problems.append("Use the public https:// address")
    if re.search(r"(localhost|127\.0\.0\.1)", url):
        problems.append(
            "That's your own computer: deploy it and use the host's address"
        )
    lowered = notes.lower()
    if "health" not in lowered:
        problems.append("Mention the /health route")
    if "secret" not in lowered and "environment" not in lowered:
        problems.append(
            "Say where the secrets live (environment variables on the host)"
        )
    if re.search(
        r"(sk-[A-Za-z0-9_-]{10,}|secret\s*=\s*['\"]?[A-Za-z0-9]{12,})",
        notes,
        re.IGNORECASE,
    ):
        problems.append(
            "Your notes seem to include a real secret: remove it and rotate it"
        )
    return problems


for p in check(URL, NOTES) or [
    "Ready: ask a friend to open the address, then ask the tutor to review it."
]:
    print("-", p)
In the lesson, you build it here and the tutor can review it.
In your own words
How do tests start clean?

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

  • 6 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

Why is get_db written with yield and a finally block?

  1. So the session is closed after every request, even when the route raises
  2. Because FastAPI only accepts dependencies that are written as generators
  3. To make the database faster by reusing the same connection every time
  4. So all requests share one session, which keeps their changes together

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