Why SQLModel?
FastAPI’s creator also built SQLModel specifically to work alongside FastAPI. It combines:- SQLAlchemy — the industry-standard Python SQL toolkit and ORM
- Pydantic — the validation library FastAPI already uses
Installation
Defining Database Models
With SQLModel,table=True tells SQLAlchemy to create an actual database table for this class:
id field is Optional because the database generates it automatically on insert — you don’t provide it.
Request and Response Schemas
Define separate schemas withouttable=True for request validation and response filtering:
Database Connection and Session Management
get_session function is a generator dependency — it opens a session, yields it to the endpoint, and automatically closes it when the request is done (even if an exception is raised).
Wiring Up the Application
lifespan context manager runs create_db_and_tables() once when the application starts, creating any missing database tables.
CRUD Endpoints with a Real Database
Key Database Operations
Always call
session.refresh(employee) after a commit() when you need to return the object. The commit() flushes changes to the database but may clear the in-memory object. refresh() reloads the latest data from the database, including auto-generated fields like id and created_at.Filtering and Querying
SQLModel’sselect() supports rich query composition:
SQLite vs PostgreSQL
- SQLite (Development)
- PostgreSQL (Production)
Updated Project Structure
database.py, models.py, and the repository layer — the Router’s interface stayed exactly the same. This is the payoff of the layered architecture you built in the previous lesson.