A minimal example demonstrating how to integrate FastAPI Users (SQLAlchemy) with SQLModel for user authentication and cross-model database relationships.
This example covers:
- Using SQLAlchemy User model (required by FastAPI Users) alongside SQLModel entities
- Defining relationships across SQLAlchemy and SQLModel models
- Running Alembic migrations in a mixed setup
- Python 3.13+
- uv package manager
-
Install dependencies:
uv sync source .venv/bin/activate
-
Initialize the database:
alembic revision --autogenerate -m "Initial migration" alembic upgrade head
-
Create sample data:
python create-sample-data.py
-
Start the server:
python main.py
-
Test the API:
# Get users (SQLAlchemy) in a group (SQLModel) curl http://localhost:8000/user-groups/1/users
fastapi-users-sqlmodel-example/
├── app/
│ ├── __init__.py
│ ├── app.py # FastAPI application & routes
│ ├── db.py # Database connection & session
│ ├── models.py # SQLAlchemy + SQLModel models
│ ├── schemas.py # Pydantic schemas
│ └── users.py # FastAPI Users configuration
├── alembic/ # Database migrations
├── alembic.ini # Alembic configuration
├── create-sample-data.py # Sample data creation script
├── main.py # Application entry point
├── pyproject.toml # Project dependencies
└── README.md
Important Differences From SQLAlchemy Example
- Set
sqlalchemy.url
inalembic.ini
to a sync URL:sqlite:///./test.db
- Add the following to
alembic/env.py
:
from app.models import SQLModel
target_metadata = SQLModel.metadata
- Add the following to
alembic/script.py.mako
:
import fastapi_users_db_sqlalchemy
import sqlmodel.sql.sqltypes
- Bind SQLModel to SQLAlchemy’s shared metadata and class registry:
SQLModel.metadata = Base.metadata
SQLModel._sa_registry = Base.registry
- Add a relationship between
User
(SQLAlchemy) andUserGroup
(SQLModel)
- Use SQLModel's
AsyncSession
instead of SQLAlchemy's - Remove the
create_db_and_tables
function in favor of Alembic
- Remove the
lifespan
event that creates tables, since Alembic is used - Add the
/user-groups/{group_id}/users
endpoint to demonstrate the relationship between SQLAlchemy and SQLModel models