Registry /
web-framework / fastapi-users-db-sqlalchemy
Install & Compatibility
Where this runs
tested against v7.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.910 runs
installs and imports cleanly · install 0.0s · import 2.923s · 87MB
glibcpy 3.10–3.910 runs
installs and imports cleanly · install 7.5s · import 2.748s · 86MB
88MB installed
● package 88MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
SQLAlchemyUserDatabase
✓ from fastapi_users.db import SQLAlchemyUserDatabase
SQLAlchemyBaseUserTable
✓ from fastapi_users.db import SQLAlchemyBaseUserTable
SQLAlchemyBaseUserTableUUID
✓ from fastapi_users.db import SQLAlchemyBaseUserTableUUID
AsyncSession
✓ from sqlalchemy.ext.asyncio import AsyncSession
DeclarativeBase
✓ from sqlalchemy.orm import DeclarativeBase
✗ from sqlalchemy.ext.declarative import declarative_base
Use DeclarativeBase for SQLAlchemy 2.0 style models; declarative_base is for SQLAlchemy 1.x or legacy modes.
This quickstart demonstrates how to set up the `fastapi-users-db-sqlalchemy` adapter with a SQLAlchemy 2.0-style User model and asynchronous database session management for FastAPI. It includes defining the User model, database engine, session maker, and the necessary dependencies (`get_async_session`, `get_user_db`). Remember to install an async database driver like `aiosqlite` or `asyncpg`.
import os
from typing import AsyncGenerator
from fastapi import Depends, FastAPI
from fastapi_users import FastAPIUsers
from fastapi_users.authentication import CookieAuthentication, AuthenticationBackend
from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
# Define your database URL (using SQLite for this example)
DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite+aiosqlite:///./test.db")
SECRET = os.environ.get("SECRET", "YOUR_SECRET_KEY") # IMPORTANT: Change in production!
# 1. Define your SQLAlchemy Base
class Base(DeclarativeBase):
pass
# 2. Define your User model
class User(SQLAlchemyBaseUserTableUUID, Base):
# You can add custom fields here
first_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
last_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
# 3. Create SQLAlchemy engine and session maker
engine = create_async_engine(DATABASE_URL)
async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
# 4. Utility function to create database tables
async def create_db_and_tables():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
# 5. Database session dependency
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
async with async_session_maker() as session:
yield session
# 6. User database adapter dependency
async def get_user_db(
session: AsyncSession = Depends(get_async_session),
) -> AsyncGenerator[SQLAlchemyUserDatabase, None]:
yield SQLAlchemyUserDatabase(session, User)
# 7. Authentication Backend (example with Cookie Authentication)
cookie_authentication = CookieAuthentication(secret=SECRET, lifetime_seconds=3600)
auth_backend = AuthenticationBackend(
name="cookie",
transport=cookie_authentication,
get_user_manager=lambda user_db: None # UserManager is typically defined outside this module
)
# Example FastAPI app (UserManager and other FastAPIUsers components needed for full functionality)
app = FastAPI()
@app.on_event("startup")
async def on_startup():
await create_db_and_tables()
# This is a minimal quickstart for the db adapter itself.
# For a full working FastAPIUsers example, you'd integrate this with FastAPIUsers, UserManager, and routers.
# Example of how you'd use get_user_db in a FastAPI route (simplified):
# @app.get("/users/me")
# async def get_current_user(
# user_db: SQLAlchemyUserDatabase = Depends(get_user_db),
# ):
# # In a real app, you'd get the current user from auth backend
# # and then use user_db to fetch more user data if needed.
# # This simply demonstrates the user_db dependency is available.
# return {"message": "User database dependency available!"}
# To run this:
# 1. Save as main.py
# 2. pip install fastapi uvicorn 'fastapi-users[sqlalchemy]' aiosqlite
# 3. uvicorn main:app --reload
Upgrade
Version history
7.0.0latest on PyPI · released Jan 4, 2025
Audit
Dependencies
fastapi-usersrequiredCore dependency for user management logic.
SQLAlchemyrequiredORM layer for database interactions.
aiosqliteoptionalAsynchronous SQLite driver, optional depending on database.
asyncpgoptionalAsynchronous PostgreSQL driver, optional depending on database.
greenletoptionalRequired by SQLAlchemy for some asyncio contexts, typically installed automatically but can be a source of 'MissingGreenlet' errors if missing.