FastAPI with a database
FastAPI doesn't include a database layer, so you choose one. The most natural fit is SQLModel, written by FastAPI's author: one class is both a Pydantic model (for validation) and a SQLAlchemy table (for the database). This lesson builds a complete CRUD API on SQLite.
Defining a table
table=Truemakes the class a database table; without it, it's just a Pydantic model.create_engine(url)sets up the connection. Swap the URL for PostgreSQL (postgresql+psycopg://user:pw@host/db) and nothing else changes.- A
Sessionis a unit of work: add objects, thencommit()to save them in one transaction. select(Hero).where(...)builds SQL safely; values are always sent as parameters.
The CRUD API
The idiomatic structure has one table model plus separate input/output models, and a dependency that gives each request its own session:
Notice how small each route is. The models handle validation and filtering; the session dependency handles connections; the route only expresses the business logic.
Relationships
Related tables are linked with a foreign key, and Relationship lets you navigate between objects:
Going further
- Migrations:
create_allonly creates missing tables; it never changes existing ones. Real projects use Alembic (alembic revision --autogenerate -m "add year", thenalembic upgrade head) to version schema changes, just like Django's migrations. - Async databases: SQLModel and SQLAlchemy also support
asyncsessions with drivers likeasyncpg, useful for very high concurrency. - Plain SQLAlchemy: SQLModel is a thin layer over SQLAlchemy 2.0, so everything SQLAlchemy can do (complex joins, window functions, bulk operations) is available.
- Indexes: add
index=Trueto columns you filter or sort on.
Practice
- Add a
GET /books/search?q=…route that finds books whose title containsq(useBook.title.contains(q)). - Add a
Reviewtable withbook_idas a foreign key and aPOST /books/{book_id}/reviewsroute. - Make
POST /booksreturn409if a book with the same title and author already exists.
1.In SQLModel, what does table=True do?
2.Why does get_session use yield instead of return?
3.What does create_all NOT do?