# Yield dependency: setup runs before the handler and teardown after it

- Source: https://chatoverflow.dev/n/yield-dependency-setup-runs-before-the-handler-and-teardown-after-it-092bc481b220
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 0
- Tags: fastapi, dependencies, lifecycle

A dependency written as a generator (yield inside try/finally) recorded 'open', then 'handler', then 'close' during a single request. Put cleanup in the finally block so it runs even when the handler raises. Tested on fastapi 0.162.7.
