Skip to content

Intro to SQLModel (or SQLAlchemy)

🎯 What You’ll Learn

  • What SQLModel is and why it’s a great fit for FastAPI
  • How SQLModel compares to SQLAlchemy and Pydantic
  • How to define your first database model
  • How to prepare for database integration in your FastAPI app

🧠 What Is SQLModel?

SQLModel is a modern ORM (Object-Relational Mapper) built by the creator of FastAPI. It combines the best of:

  • SQLAlchemy: for powerful database access and schema generation
  • Pydantic: for data validation and serialization

This makes SQLModel ideal for FastAPI because:

  • You define your data models once and use them for both database and API validation
  • It supports both ORM mode (for database interaction) and Pydantic mode (for request/response validation)
  • It’s fully type-safe and integrates seamlessly with FastAPI

🔍 SQLModel vs SQLAlchemy vs Pydantic

Feature SQLAlchemy Pydantic SQLModel (✅)
Database ORM ✅ Yes ❌ No ✅ Yes (via SQLAlchemy)
Data validation ❌ No ✅ Yes ✅ Yes (via Pydantic)
Type hints ⚠️ Partial ✅ Yes ✅ Yes
FastAPI integration ⚠️ Manual ✅ Yes ✅ Seamless
One model for all layers ❌ No ❌ No ✅ Yes

📦 Installing SQLModel and SQLite

We’ll use SQLite for simplicity — it’s file-based and requires no setup.

pip install sqlmodel

🧱 Step-by-Step: Define a SQLModel Task

Let’s define a Task model that maps to a database table.

📄 models/task.py

from sqlmodel import SQLModel, Field
from typing import Optional

class Task(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    title: str
    description: Optional[str] = None
    completed: bool = False

🔍 Key Concepts

  • SQLModel is the base class (inherits from both Pydantic and SQLAlchemy)
  • table=True tells SQLModel to create a table for this model
  • Field(..., primary_key=True) marks id as the primary key
  • Optional[int] with default=None allows auto-incrementing IDs

🧰 What’s Next?

In the next lesson, you’ll:

  • Set up a SQLite database
  • Create the tables from your models
  • Use SQLModel’s session system to perform CRUD operations

🧠 Practice Challenge

Before moving on, try this:

  • Add a created_at: datetime field to the Task model
  • Set it to default to the current time using Field(default_factory=datetime.utcnow)

Let me know when you’re ready to move on to Creating models and tables with SQLModel, or if you want to explore SQLModel’s hybrid nature in more depth first.