Create an engine and session factory once, and provide a session per request through a dependency that yields it and closes it afterwards; keep database models (ORM) separate from Pydantic schemas.
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column, sessionmaker
engine = create_engine(DATABASE_URL, pool_size=10, max_overflow=20, pool_pre_ping=True)
SessionLocal = sessionmaker(bind=engine, autoflush=False)
class Base(DeclarativeBase):
pass
class ItemRow(Base):
__tablename__ = "items"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
price: Mapped[float]
def get_db():
with SessionLocal() as db:
yield db
@app.get("/items/{item_id}", response_model=ItemOut)
def read_item(item_id: int, db: Session = Depends(get_db)):
row = db.get(ItemRow, item_id)
if row is None:
raise HTTPException(status_code=404, detail="Item not found")
return row