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:
ExpenseandExpenseUpdateare imported frommodels— the class definitions that used to live inmain.pyhave been removedcreate_db_and_tablesandget_sessionare imported fromdatabaseasynccontextmanagerand 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()
yieldCode 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.
- Import
SessionDepfromdatabase. Add it to the existing import line that already brings increate_db_and_tablesandget_session. - Define the
lifespanfunction above theapp = FastAPI(...)line:- Add the
@asynccontextmanagerdecorator. - Define
async def lifespan(app: FastAPI):. - Inside the function, call
create_db_and_tables(), thenyield.
- Add the
- Add
lifespan=lifespanto theFastAPI()call.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding