Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DJ
Django & FastAPI
0/12 completed
Beginner
How Python web frameworks workYour first FastAPI appRequest bodies and Pydantic models
Intermediate
FastAPI with a databaseDependencies, routers and testingDjango: projects, apps and the ORMDjango views, URLs and templatesForms, the admin and class-based views
Advanced
APIs with Django REST frameworkAuthentication in Django and FastAPIBackground tasks and async
Pro
Deploying Python web apps
Tracks / Django & FastAPI / Intermediate

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

Python · editable
  • table=True makes 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 Session is a unit of work: add objects, then commit() 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:

Python · editable

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:

Python · editable

Going further

  • Migrations: create_all only creates missing tables; it never changes existing ones. Real projects use Alembic (alembic revision --autogenerate -m "add year", then alembic upgrade head) to version schema changes, just like Django's migrations.
  • Async databases: SQLModel and SQLAlchemy also support async sessions with drivers like asyncpg, 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=True to columns you filter or sort on.

Practice

  1. Add a GET /books/search?q=… route that finds books whose title contains q (use Book.title.contains(q)).
  2. Add a Review table with book_id as a foreign key and a POST /books/{book_id}/reviews route.
  3. Make POST /books return 409 if a book with the same title and author already exists.
✎ Check your understanding

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?

← Request bodies and Pydantic models