Dependency Injection
Each database-backed handler currently repeats with SessionFactory() as session: to create a session and close it afterward.
FastAPI's dependency injection lets us centralize session management. A dependency is an object or capability a function needs, such as a database session. Injection means preparing it outside the function and passing it in. Here, FastAPI prepares a session outside the handler and provides it to the handler.
Below SessionFactory in connection.py, add a session management function:
def get_session():
with SessionFactory() as session:
yield session
yield produces a value and pauses the function. When execution resumes, it continues after yield.
In main.py, use Depends(get_session) to inject a session into the list API:
from fastapi import Depends
from sqlalchemy.orm import Session
from connection import get_session
@app.get(
"/posts",
summary="List all posts",
response_model=list[PostResponse],
)
def get_posts_handler(session: Session = Depends(get_session)):
statement = select(Post)
posts = session.scalars(statement).all()
return posts
Depends() tells FastAPI which function supplies a parameter's value. FastAPI calls get_session(), receives the yielded session, and passes it to the handler. After response processing, FastAPI resumes the dependency after yield. Leaving the with block closes the session automatically.
We delegate the session management function's lifecycle to FastAPI. Multiple APIs can reuse get_session, while each handler focuses on querying or saving data with the supplied session.
Update the other post APIs the same way. Add session: Session = Depends(get_session), remove the with wrapper, and unindent its body one level. Once all handlers are updated, remove the SessionFactory import from main.py.
Dependency injection is also useful for shared operations such as authentication and permission checks. We will revisit it in the login exercises.
Check Your Understanding
Decide whether each statement is true or false.
- Dependency injection lets a function receive required objects from outside.
- A handler must directly call the dependency function registered with Depends.
- A dependency using yield can perform cleanup after providing its value.
Answers and Explanations
- True — Objects prepared elsewhere can be passed as parameters.
- False — FastAPI calls the dependency and supplies its result.
- True — FastAPI resumes execution after yield to allow resource cleanup.