fastapi-sqlalchemy
raw JSON → 0.2.1 verified Mon Apr 27 auth: no python maintenance
Provides a simple middleware and dependency to integrate SQLAlchemy sessions into FastAPI applications. Current version 0.2.1, last updated in 2021. Low release cadence; considered stable but minimal maintenance.
pip install fastapi-sqlalchemy Common errors
error RuntimeError: No database session found. Have you added the DBSessionMiddleware? ↓
cause Accessing `db.session` before the middleware has been added or outside a request context.
fix
Ensure
app.add_middleware(DBSessionMiddleware, db_url=...) is called before any route that uses db. error AttributeError: module 'fastapi_sqlalchemy' has no attribute 'DBSessionMiddleware' ↓
cause Importing from the wrong module path or outdated pip package.
fix
Use
from fastapi_sqlalchemy import DBSessionMiddleware (no submodule). error sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: ... ↓
cause Tables not created because the middleware does not auto-create tables.
fix
Use
Base.metadata.create_all(bind=engine) before starting the app, using the same engine URL. Warnings
gotcha The `db` object is a thread-local proxy and must be accessed within the request lifecycle. Using it outside of a request context (e.g., at module level) will raise an error. ↓
fix Always access `db` inside a FastAPI route or dependency.
deprecated The library is not actively maintained (last release 2021) and does not support newer SQLAlchemy 2.0 style. It uses the deprecated `Session` pattern. ↓
fix Consider switching to FastAPI's built-in SQLAlchemy support with `Session` dependency injection or use sqlalchemy.ext.asyncio for async.
gotcha The middleware does not handle database disconnections or connection pooling gracefully by default. Long-running applications may experience stale connections. ↓
fix Manually configure engine with `pool_pre_ping=True` using `engine_args` parameter in middleware.
Imports
- DBSessionMiddleware wrong
from fastapi_sqlalchemy.middleware import DBSessionMiddlewarecorrectfrom fastapi_sqlalchemy import DBSessionMiddleware - db wrong
from fastapi_sqlalchemy.db import dbcorrectfrom fastapi_sqlalchemy import db
Quickstart
import os
from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware, db
from sqlalchemy import create_engine
app = FastAPI()
DATABASE_URL = os.environ.get('DATABASE_URL', 'sqlite:///test.db')
app.add_middleware(DBSessionMiddleware, db_url=DATABASE_URL)
@app.get('/')
def root():
# db.session is the current SQLAlchemy session
result = db.session.execute('SELECT 1').scalar()
return {'result': result}