Python: post #2263646 — TG.ME

👋 Hello everyone!
I hope you guys are familiar with FastAPI, SQLModel, and Pydantic. I’m trying to understand something by reading the docs about how SessionDep works in FastAPI 🙏
When i came across the examples
def get_session():
with Session(engine) as session:
yield session

@app.post("/heroes/"):
def create_hero(hero: Hero, session: SessionDep) -> Hero:
session.add(hero)
session.commit()
session.refresh(hero)
return hero

My understanding is that when create_hero() starts executing by my fastapi get a request from user's browser, the session comes from get_session(), which means the function is effectively running while the with Session(engine) as session: context is active. Is that correct? 🤔 i think Yes.

Now, suppose I have a routes.py function that does several different things:
def some_route(..., session: SessionDep):
# some other tracking, keep record, loggin work...
if some_condition:
# database-related work
# suppose non-database work...

In this case, I don’t necessarily want the entire route function to depend on or use the database session. I would rather keep the database-related logic inside a separate function/service, and only pass/use the session there when database work is actually needed.
For example, something conceptually like:
def do_database_work(..., session:SEssionDep):
# database operations here

def some_route(...):
# other work...

if some_condition:
do_database_work(..., session)

My questions:
Is my understanding of SessionDep and the with Session(...) context correct?
Is there a recommended/best-practice way in FastAPI/SQLModel to avoid injecting SessionDep outside the routes function. as i see the docs they use the SessionDep in the routes function directly, but maybe based on the application i will make the requirements is not always talking with database or conditionally.

What is the cleanest architecture for handling this in a real FastAPI project i think to not pass the SessionDep in the routs funciton, so where you say to keep this part and how when i will resturcter the routes fun small and call others function to do the work.
? 🏗
❤1
August 24, 2026