Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Authentication

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Authentication

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

GET / goes from the browser to the router, which picks index. Depends(get_db) hands index a session. SQLAlchemy sends SQL to SQLite, rows come back as Post objects, Jinja2 turns them into HTML, and the response returns with status 200. Browser GET / Router picks index Depends get_db SQLAlchemy 2 SELECTs SQLite blog.db Response 200 text/html Jinja2 index.html rows become Post objects after the response, get_db closes the session
The home page trip. No cookie yet: nobody has logged in.

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 session cookie has three parts joined by dots: a base64 payload that decodes to user_id 1, a timestamp, and a 27-character signature made with the SECRET_KEY. Anyone can read the payload; changing it breaks the signature. payload (base64) {"user_id": 1} . timestamp 6 chars . signature 27 chars, needs SECRET_KEY anyone can read it nobody can forge it without the key Signed, not encrypted. Nothing about the login is written to the database.
The boarding pass: the data travels in the cookie itself, and the signature is the stamp.

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
WhoGET and POST /admin/createPosts in the database
Anonymous401 {"detail":"Not authenticated"}unchanged
Plain test user403 {"detail":"Not authorized"}5 before, 5 after
AdminPOST: 303 to /post/65 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
Bar chart of when three concurrent slow requests finish: async def with a blocking session 1.92 s and the ping waits 1.83 s; plain def 0.88 s; async def with AsyncSession 1.16 s. In the last two the ping does not wait. async def + Session 1.92 s ping waits 1.83 s def + Session 0.88 s, ping 0.0 s async def + AsyncSession 1.16 s, ping 0.0 s One slow request alone takes 0.69 s. Times are when the last of three finished.
Same query, three ways. Only the first one makes a tiny ping wait behind it.

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_KEY in the code. Whoever knows it can sign a cookie for any user_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 def over a blocking session. It looks faster and makes every other request wait.

Quick recap

StepWhat happensIn the run
GET /router, Depends(get_db), SQLAlchemy, Jinja22 SELECTs, 200, no cookie
POST /loginone SELECT by email, bcrypt verifywrong: 200 with error; right: 303
Session cookiepayload.timestamp.signature, httponlydecodes to {"user_id": 1}
Next requestsignature checked, then require_admin200; changed cookie: 401
Write routeguest 401, plain user 403, admin 303posts 5, 5, then 6
Registeris_admin = email == ADMIN_EMAILfirst match becomes admin
Timingasync def + blocking session1.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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 25 of 26

Previous
Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
Next post
Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks

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)

Related posts

Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks

A made-up customer, Acme Retail, has a company login, a CRM with its own field names, old orders in a nightly CSV and order.updated webhooks. Instead of rewiring the Support Copilot, put one small adapter at each edge: a token check, a chained order source and a signature check, with two tests per edge.

On this page

  • Passport once, boarding pass after
  • One GET, end to end
  • The router picks the function
  • Depends hands over a session
  • Two SQL statements for the home page
  • The login: one SELECT and a bcrypt check
  • Hashed, not encrypted
  • A signed session cookie
  • The next request carries the cookie
  • require_admin: 401 or 403
  • Who becomes admin?
  • async def over a blocking session
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.