Write the Session Generator
Exit

Write the Session Generator

Add get_session and SessionDep to database.py to give each request its own database session

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

What a session is

A session is a short-lived workspace for database operations. When a request comes in, a session opens. Your endpoint reads or writes through the session. When the endpoint finishes, the session commits any changes and closes.

This replaces the old pattern of reading from and writing to the expenses dict directly. With a session, every change is part of a transaction — if anything fails, the changes are rolled back automatically.

The yield pattern

get_session() is a generator function. It uses yield instead of return:

def get_session():
    with Session(engine) as session:
        yield session

  • The with Session(engine) as session: block opens a session and guarantees it will be closed when the block exits — even if the endpoint raises an error.
  • yield session pauses the function and hands the session to the endpoint. When the endpoint finishes, get_session() resumes and the with block closes the session.

yield means "give this to whoever is waiting, then resume when they are done." You will use this same pattern again in the next chapter.

SessionDep

SessionDep is a type alias that combines the Session type with Depends(get_session). Instead of writing Annotated[Session, Depends(get_session)] in every endpoint signature, you write session: SessionDep.

SessionDep = Annotated[Session, Depends(get_session)]

Depends(get_session) tells FastAPI to call get_session() before the endpoint runs and inject the result as the session parameter. Each request gets its own session, opened fresh and closed when the response is sent.

Instructions

Add the session generator and SessionDep type alias to database.py.

  1. Add Session to the import from sqlmodel. Also add Annotated and Depends — import Annotated from typing and Depends from fastapi.
  2. Define a function called get_session. Inside it, open a with Session(engine) as session: block and yield session. This gives each request its own session and ensures the session closes when the request finishes.
  3. Below the function, define SessionDep = Annotated[Session, Depends(get_session)]. You will use this in endpoint signatures to tell FastAPI to inject a session automatically.