How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
Follow GET / through the FastAPI blog to two SQL statements and an HTML page, then a login: one SELECT, a bcrypt check, a 303 with a signed session cookie that decodes to user_id 1. A changed cookie gets 401, a plain user 403, and three slow requests on async def with a blocking session finish at 1.92 s while a ping waits 1.83 s.
What you will learn
- Trace one GET through a FastAPI blog: router, Depends(get_db), SQLAlchemy, Jinja2 and back
- Explain what a login stores: a bcrypt hash in the database and a signed, readable session cookie in the browser
- Read require_admin and say why a guest gets 401 and a plain user gets 403
- Measure why async def over a blocking SQLAlchemy session holds up every other request, and pick a fix
Before you start
- FastAPI routes and Depends
- SQLAlchemy sessions with get_db
- Python async and await
Knowing the files of a project tells you what's there. Knowing the flow tells you what runs, and in which order. That's what you need when you review code an AI tool wrote for you.
In this article we trace one request through our FastAPI blog, from the browser to the database and back. Then we trace a login and see exactly what the blog keeps after you type your password. At the end we measure what async def really does for this blog. Every output below comes from a real run of the designed blog (FastAPI 0.136.1, SQLAlchemy 2.0.36, passlib 1.7.4, bcrypt 4.0.1), with one small file added for timing. If the files are new to you, start with the folder tour.
Passport once, boarding pass after
At an airport you show your passport once, at check-in. You get a boarding pass with a stamp the airline can check. At every gate after that you only show the pass. And if someone writes a new seat on the pass by hand, the stamp doesn't match and the gate turns them away.
In the blog, the passport check is the login, the boarding pass is the session cookie, and the stamp is a signature.
One GET, end to end
The router picks the function
app/main.py adds three routers with include_router. Asking the app which function sits behind each path gives this:
GET /login login_page (app/routes/auth.py:82) async=True
POST /login login (app/routes/auth.py:90) async=True
GET / index (app/routes/posts.py:13) async=True
GET /admin/create create_post_page (app/routes/posts.py:36) async=True
POST /admin/create create_post (app/routes/posts.py:41) async=True
The router is a lookup table: it matches the method and the path, and nothing more. /login has two functions, one to show the form and one to handle it. And every one of them is async def. Keep that in mind.
Depends hands over a session
@router.get("/", response_class=HTMLResponse)
async def index(request: Request, db: Session = Depends(get_db)):
posts = db.query(Post).order_by(Post.created_at.desc()).all()
user = get_current_user(request, db)
return templates.TemplateResponse(request=request, name="index.html", context={"posts": posts, "user": user})
Depends(get_db) tells FastAPI to call get_db first and pass in what it gives. get_db makes a session from SessionLocal, yields it to index, and waits at the yield. When the response is done, its finally block closes the session. Every request gets its own session, and every session gets closed, even if something fails. (More on Depends in path, query, body and Depends.)
Two SQL statements for the home page
With SQL logging on, the home page ran exactly two statements:
SELECT posts.id AS posts_id, posts.title AS posts_title, posts.content AS posts_content, posts.author_id AS posts_author_id, posts.created_at AS posts_created_at, posts.updated_at AS posts_updated_at FROM posts ORDER BY posts.created_at DESC
SELECT users.id AS users_id, users.email AS users_email, users.username AS users_username, users.hashed_password AS users_hashed_password, users.is_admin AS users_is_admin, users.created_at AS users_created_at FROM users WHERE users.id = ?
The first is db.query(Post) with the newest first. Then get_current_user looks in the session for a user_id. We're not logged in, so there isn't one, and it doesn't even ask the database. The second SELECT comes from the template: it prints post.author.username, so SQLAlchemy loads the author.
The answer: status 200, text/html; charset=utf-8, title "Home - Blog", and no cookie.
The login: one SELECT and a bcrypt check
The login form sends POST /login with two fields:
@router.post("/login")
async def login(
request: Request,
email: str = Form(...),
password: str = Form(...),
db: Session = Depends(get_db)
):
user = authenticate_user(db, email, password)
if not user:
return templates.TemplateResponse(
request=request,
name="login.html",
context={"error": "Invalid email or password", "user": None}
)
request.session["user_id"] = user.id
return RedirectResponse(url="/", status_code=status.HTTP_303_SEE_OTHER)
Form(...) tells FastAPI to read that field from the form body. authenticate_user in app/auth.py runs one query and one check:
def authenticate_user(db: Session, email: str, password: str):
user = db.query(User).filter(User.email == email).first()
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
The SQL it sends is SELECT ... FROM users WHERE users.email = ? LIMIT ? OFFSET ?. With a wrong password the answer is 200, the login page again with "Invalid email or password", and no cookie.
Hashed, not encrypted
The password itself is never stored. passlib with bcrypt hashes it, and a hash only goes one way, so there is nothing to decrypt. Here's what the run found in the seeded admin's hashed_password:
prefix $2b$12$ (2b = bcrypt, 12 = cost)
length 60
salt 22 chars, digest 31 chars
plain password inside: False
verify right password: True
verify wrong password: False
same password hashed again is different: True
A new random salt each time is why the same password gives a different hash. To check a login, bcrypt reads the salt and cost from the stored hash, hashes what you typed the same way, and compares.
One catch: bcrypt only uses the first 72 bytes. Register refuses anything longer, but verify_password quietly cuts what you type, so a longer password with the same first 72 bytes still logs in:
72 a's vs 72 a's + 8 more letters verify: True
POST /register with 73 bytes -> 200 'Password is too long (max 72 bytes)'
A signed session cookie
After a good password, the route sets request.session["user_id"]. That session comes from Starlette's SessionMiddleware, which app/main.py adds with a secret key. The run captured the answer:
status 303 -> /
Set-Cookie name session
attributes ['path', 'max-age', 'httponly', 'samesite']
value parts 3 (payload.timestamp.signature)
payload decoded {"user_id": 1}
signature length 27
The cookie is httponly, so page scripts can't read it. It is signed, not encrypted: decode the first part and anyone sees {"user_id": 1}, but nobody can change it without the secret key. And nothing was written to the database at login. If .env is missing, though, the secret falls back to a fixed string written in the code, and anyone who knows that string could sign their own cookie. Always set SECRET_KEY.
The next request carries the cookie
The browser now asks for /admin/create and sends the cookie along. SessionMiddleware checks the signature, it matches, and request.session holds user_id 1. The route depends on require_admin, which runs one query, SELECT ... FROM users WHERE users.id = ?. The admin passes, and the answer is 200 with the title "Create Post - Blog".
Then we changed one character in the cookie and sent it again:
status 401
body {"detail":"Not authenticated"}
The signature no longer matched, the session came up empty, and the guard said no. The cookie is checked again on every request, and that's how you stay logged in from page to page.
require_admin: 401 or 403
def require_auth(request: Request, db: Session = Depends(get_db)):
user = get_current_user(request, db)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated"
)
return user
def require_admin(request: Request, db: Session = Depends(get_db)):
user = require_auth(request, db)
if not user.is_admin:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authorized"
)
return user
| Who | GET and POST /admin/create | Posts in the database |
|---|---|---|
| Anonymous | 401 {"detail":"Not authenticated"} | unchanged |
| Plain test user | 403 {"detail":"Not authorized"} | 5 before, 5 after |
| Admin | POST: 303 to /post/6 | 5 before, 6 after |
401 means the app doesn't know who you are. 403 means it knows, and you're not allowed. The admin's POST ran an INSERT INTO posts (title, content, author_id, created_at, updated_at) after the user lookup. The check sits in the backend, in a dependency, and it runs before the route can touch the posts. One small thing for the review: a guest who opens the write page sees a raw JSON line instead of the login page.
Who becomes admin?
The check is in the right place. So who gets is_admin = True? Look at routes/auth.py, line 62, inside register:
# Create user
is_admin = email == ADMIN_EMAIL
hashed_password = get_password_hash(password)
We tried it on an empty database, registering with the ADMIN_EMAIL value from .env:
status 303 -> /
session cookie set ['session']
is_admin True
no email check, no invite: the string match is the whole test
Nobody checks that you own the address. Whoever registers first with it becomes the admin. That's a review finding: the admin flag should only be set from a trusted place, like the seed script or a command run on the server, never from a public form. Django's blog makes the same point in a different way (see the Django request and login flow), and so does the Flask one.
async def over a blocking session
Now back to all those async def functions. All async def routes share one event loop, one worker that takes turns between requests, and it can only switch at an await. In index, db.query(...) has no await, because the session is a normal, blocking one. So while a query runs, the loop is stuck and every other request waits, even a tiny one. The basics of this, with a one-second sleep, are in SQLAlchemy models and migrations. Here we measure it on the blog itself.
We added one file, app/routes/timing.py, with a slow query, three routes that run it and a ping:
from fastapi import APIRouter, Depends
from sqlalchemy import text
from sqlalchemy.ext.asyncio import (
async_sessionmaker, create_async_engine)
from sqlalchemy.orm import Session
from app.database import get_db
router = APIRouter(prefix="/timing")
SLOW = text(
"WITH RECURSIVE c(x) AS (SELECT 1 UNION ALL "
"SELECT x + 1 FROM c WHERE x < 3000000) "
"SELECT count(*) FROM c"
)
async_engine = create_async_engine("sqlite+aiosqlite:///./blog.db")
AsyncSessionLocal = async_sessionmaker(async_engine)
@router.get("/ping")
async def ping():
return {"ok": True}
@router.get("/slow-async")
async def slow_async(db: Session = Depends(get_db)):
return {"count": db.execute(SLOW).scalar()}
@router.get("/slow-def")
def slow_def(db: Session = Depends(get_db)):
return {"count": db.execute(SLOW).scalar()}
@router.get("/slow-asyncsession")
async def slow_asyncsession():
async with AsyncSessionLocal() as session:
result = await session.execute(SLOW)
return {"count": result.scalar()}
timing_app.py just imports the blog's app and adds this router. Then uvicorn served it, and we sent three slow requests at once plus one ping:
one slow request alone: 0.69 s
ping when idle: 0.004 s
async def + blocking Session: 3 slow requests finish at [1.92, 1.92, 1.92] s, ping took 1.83 s
def + blocking Session: 3 slow requests finish at [0.78, 0.85, 0.88] s, ping took 0.0 s
async def + AsyncSession: 3 slow requests finish at [1.11, 1.15, 1.16] s, ping took 0.0 s
On the async def route with the blocking session, the three requests ran one after another, and the ping, which should take 4 milliseconds, waited 1.83 seconds behind them. With plain def, FastAPI ran each request in its thread pool, and the ping came back at once. With an AsyncSession, the query is awaited, so the loop stays free.
So there are two fixes. The small one is to write def instead of async def on routes that use the blocking session. The bigger one is an async engine, AsyncSession and an await on every query, all the way down. In this blog no route awaits anything, so def is the smaller fix. The rule: async def only helps when the work inside awaits, and a blocking call inside it is worse than plain def.
Common mistakes
- Calling the session cookie encrypted. Starlette signs it. The payload is plain base64 that anyone can decode, so never put secrets in
request.session. - Leaving a default
SECRET_KEYin the code. Whoever knows it can sign a cookie for anyuser_id. - Mixing up 401 and 403. 401 is "who are you?", 403 is "I know you, and no".
- Deciding the admin in a public form. A string match on an email is not proof of anything.
async defover a blocking session. It looks faster and makes every other request wait.
Quick recap
| Step | What happens | In the run |
|---|---|---|
| GET / | router, Depends(get_db), SQLAlchemy, Jinja2 | 2 SELECTs, 200, no cookie |
| POST /login | one SELECT by email, bcrypt verify | wrong: 200 with error; right: 303 |
| Session cookie | payload.timestamp.signature, httponly | decodes to {"user_id": 1} |
| Next request | signature checked, then require_admin | 200; changed cookie: 401 |
| Write route | guest 401, plain user 403, admin 303 | posts 5, 5, then 6 |
| Register | is_admin = email == ADMIN_EMAIL | first match becomes admin |
| Timing | async def + blocking session | 1.92 s, ping waits 1.83 s |
Try it yourself
Log in, copy the session cookie from your browser's developer tools, and decode the part before the first dot with base64 in Python to see your user id. Then change one letter in it and reload the write page.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)