Master FastAPI dependency injection for building modular, testable APIs.
View on GitHubTheBushidoCollective/han
jutsu-fastapi
January 24, 2026
Select agents to install to:
npx add-skill https://github.com/TheBushidoCollective/han/blob/main/jutsu/jutsu-fastapi/skills/fastapi-dependency-injection/SKILL.md -a claude-code --skill fastapi-dependency-injectionInstallation paths:
.claude/skills/fastapi-dependency-injection/# FastAPI Dependency Injection
Master FastAPI's dependency injection system for building modular,
testable APIs with reusable dependencies.
## Basic Dependencies
Simple dependency injection patterns in FastAPI.
```python
from fastapi import Depends, FastAPI
app = FastAPI()
def get_db():
db = Database()
try:
yield db
finally:
db.close()
@app.get('/users')
async def get_users(db = Depends(get_db)):
return await db.query('SELECT * FROM users')
# Simple function dependency
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {'q': q, 'skip': skip, 'limit': limit}
@app.get('/items')
async def read_items(commons: dict = Depends(common_parameters)):
return commons
# Async dependencies
async def get_async_db():
db = await AsyncDatabase.connect()
try:
yield db
finally:
await db.disconnect()
@app.get('/async-users')
async def get_async_users(db = Depends(get_async_db)):
return await db.fetch_all('SELECT * FROM users')
```
## Dependency Scopes
Understand dependency lifecycle and caching.
```python
from fastapi import Depends
# Request-scoped dependency (default, cached per request)
def get_current_user(token: str = Depends(oauth2_scheme)):
user = decode_token(token)
return user
# Multiple uses in same request reuse the same instance
@app.get('/profile')
async def get_profile(
user1 = Depends(get_current_user),
user2 = Depends(get_current_user) # Same instance as user1
):
assert user1 is user2 # True
return user1
# No caching (use_cache=False)
def get_fresh_data(use_cache: bool = False):
return fetch_from_api()
@app.get('/data')
async def get_data(data = Depends(get_fresh_data, use_cache=False)):
return data # Fetches fresh data each time
# Singleton pattern (application scope)
class Settings:
def __init__(self):
self.app_name = "MyApp"
self.admin_email = "admin@example.com"
settings = Settings() # Created o