-
Notifications
You must be signed in to change notification settings - Fork 0
FastAPI Programming Notes
James Brucker edited this page Jun 18, 2025
·
7 revisions
In FastAPI you need a reference to a Session and/or an Engine. Create them using SqlAlchemy.
DATABASE_URL = "sqlite:///./example.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": True}) # False?
# a factory method for Sessions
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_session() -> Session:
session = SessionLocal()
try:
yield session
finally:
session.close()Dependency injection:
fastapi = FastAPI()
@fastapi.post("/users/", response_model=User)
def create_user(user: User, session: Session = Depends(get_session)):
session.add(**user)
session.commit()
session.refresh(user)