Wire Up the Database in main.py
Exit

Wire Up the Database in main.py

Connect the database lifecycle to your app with the lifespan function and SessionDep

💻

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

What changed in main.py

You can see models.py and database.py in the read-only tabs. The imports in main.py already reflect this restructuring:

  • Expense and ExpenseUpdate are imported from models — the class definitions that used to live in main.py have been removed
  • create_db_and_tables and get_session are imported from database
  • asynccontextmanager and the FastAPI/SQLModel imports are ready

The JSON storage functions (save_expenses, load_expenses) and the endpoints are still in their old form. You will replace those in Lesson 2.

Your job in this chapter

Two things remain:

Add SessionDep. This type alias tells FastAPI to inject a database session into any endpoint that asks for one. You defined it in database.py — now import and use it in main.py.

Add the lifespan function. FastAPI's lifespan parameter accepts a context manager that runs setup code before the app starts serving requests:

@asynccontextmanager
async def lifespan(app: FastAPI):
    create_db_and_tables()
    yield

Code before yield runs on startup. The yield is required — it marks where the app runs. Code after yield would run on shutdown.

Pass lifespan=lifespan to FastAPI() to register it.

Instructions

Connect the database to your app.

  1. Import SessionDep from database. Add it to the existing import line that already brings in create_db_and_tables and get_session.
  2. Define the lifespan function above the app = FastAPI(...) line:
    • Add the @asynccontextmanager decorator.
    • Define async def lifespan(app: FastAPI):.
    • Inside the function, call create_db_and_tables(), then yield.
  3. Add lifespan=lifespan to the FastAPI() call.