Dependency with yield
noun
say it: “dih-PEN-den-see with YEELD” /dɪˈpɛndənsi wɪð jiːld/
A FastAPI dependency that hands a value to the route with yield and runs its cleanup code after the answer has gone, such as closing a database connection.
What is Dependency with yield?
A dependency with yield gives a value to the endpoint, then runs cleanup code after the response, perfect for opening and closing a database session.
def get_session():
with Session(engine) as session:
yield session # closed after the request
In a sentence
- “Because it's a dependency with yield, the connection closes even when the route raises.”
- “get_db is a dependency with yield: it opens the connection, yields it, then closes it.”
Level: Freelancer · More FastAPI terms at this level
Updated