What is the purpose of yield in a dependency function?
Tests teardown logic in FastAPI dependencies. Yield splits setup from cleanup: code before yield runs pre-request, after yield runs post-response to close resources like DB sessions. Red flag: confusing it with return or thinking yield is only for generators.
WHAT THIS TESTS: This question tests whether you understand dependency lifecycle management in FastAPI, specifically the difference between return and yield in dependency functions. Interviewers want to know if you can reason about setup and teardown phases, resource cleanup, and the request-response lifecycle. It also reveals whether you understand that FastAPI dependencies can act like asynchronous context managers without requiring explicit context manager syntax or decorator boilerplate.
A GOOD ANSWER COVERS: First, state that yield turns the dependency into a generator, allowing code to run both before and after the request handler completes. Second, explain that everything before the yield statement is setup logic, the yielded value is injected into the path operation function, and everything after the yield is teardown logic that executes after the response is fully sent. Third, give the database session example: create the session, yield it for the endpoint to use, then close it in a finally block or directly after the yield. Fourth, mention that this pattern works with both sync and async dependencies and that FastAPI automatically handles the generator protocol under the hood.
COMMON WRONG ANSWERS: A red flag is saying yield is only for creating iterators or memory-efficient sequences. Another mistake is claiming the cleanup code runs before the response is sent, or that yield behaves exactly like return but with multiple values. Some candidates incorrectly state that you need to manually call next on the generator or wrap it in a context manager class for FastAPI to use it. Confusing synchronous yield with async yield and not knowing that code after yield runs post-response is also a significant gap that signals shallow framework knowledge.
LIKELY FOLLOW-UPS: The interviewer may ask what happens if an exception is raised in the path operation, in which case you should explain using try finally or except blocks around the yield to guarantee cleanup. They might ask about sub-dependencies with yield and execution order when multiple dependencies are nested. Another angle is how yield interacts with BackgroundTasks, since background tasks run after the response but before dependency cleanup finishes. They may also ask you to compare yield dependencies to lifespan events or ASGI middleware.
ONE CONCRETE EXAMPLE: A concrete example is a SQLAlchemy async database dependency. You define async def get_db that instantiates an AsyncSession, yields the session object to the endpoint, and then awaits session.close in a finally block. The endpoint receives the active session, executes queries, returns a JSON response, and only then does the dependency resume after the yield to close the database connection. This ensures the session lifetime is strictly bound to the request and connection leaks are impossible.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.