FastAPI Dependency Injection
FastAPI's built-in system for sharing reusable logic across route handlers.
Definition
FastAPI's dependency injection system allows you to declare shared logic — database sessions, authentication, rate limiting, settings — as `Depends()` parameters. FastAPI automatically resolves and caches these dependencies per request, handling teardown (like closing database sessions) automatically.
Why it matters for AI APIs
Dependency injection eliminates boilerplate in route handlers and makes code testable. Instead of opening a database connection in every function, you declare `db: AsyncSession = Depends(get_db)` and FastAPI handles the rest. This is the idiomatic FastAPI pattern for production code.
In FastAPI AI Kit
The kit uses dependencies extensively: `Depends(get_db)` for async database sessions, `Depends(get_api_key)` for authenticated API key extraction, `Depends(get_current_user)` for JWT validation, and custom `@rate_limit` decorators that internally use Depends for Redis counters.
