fastapi-dependency-injection
FastAPI dependency-injection patterns and anti-patterns -- request-scoped auth tokens leaking into singleton DI graphs, missing `Depends()` declarations on…
Skill by MILTONADINA
Install
Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.
npx agentmarket install skill/miltonadina-fastapi-dependency-injection
Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.
Get the weekly diff
The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.
About
Use cases: backend, security
Reviews
Write a reviewNo reviews yet. Installed it? Reviews come from verified installers only. How reviews work
Permissions
What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.
- Tools
- No tools found
- Secrets
- None asked for
- Install scripts
- None found
Network hosts it talks to 1
codeload.github.com· found in install command
Files it touches
~/.claude/skills/fastapi-dependency-injection
What's inside
- Skill name
fastapi-dependency-injection- Description
- FastAPI dependency-injection patterns and anti-patterns -- request-scoped auth tokens leaking into singleton DI graphs, missing `Depends()` declarations on auth-required routes, `dependency_overrides` mis-use leaking a fake identity across tests. Triggers on FastAPI route authoring (`@app.get`, `@app.post`, `Depends()` references). OWASP ASI03 (Identity & Privilege Abuse) defense for auth-token handling via DI.
- License
- MIT
- Instructions
- 292 lines in SKILL.md · view on GitHub
Agent Skills spec issues
- name: "fastapi-dependency-injection" does not match folder "dependency-injection"
Files (1)
- SKILL.md
SKILL.md (first lines)
# FastAPI Dependency Injection
> Defends against **OWASP ASI03 (Identity & Privilege Abuse)** in
> FastAPI applications where the DI graph carries auth-relevant state.
> FastAPI's DI system is ergonomic for wiring shared dependencies
> (database sessions, settings, repositories), but its scoping model is
> per-request only by default -- and that semantic interacts subtly with
> auth-token handling. Without the patterns here, request-scoped
> identity can leak across requests via inadvertent caching, or
> auth-required routes can ship without an enforced auth check because
> the DI declaration was forgotten.
**Tradeoff:** Explicit `Depends()` declarations on every auth-required
route is repetitive vs. relying on global middleware. Worth it:
per-route auth dependencies are reviewable in isolation, can be
overridden in tests for the specific route, and produce typed access
to the authenticated identity inside the handler. Middleware-only auth
hides the contract from the handler signature.
---
## Why this matters
FastAPI's `Depends()` system resolves dependencies per request by
default -- new database session, fresh auth check, freshly-loaded
settings. But the framework also supports `lru_cache`-style memoization
for expensive dependencies (settings loading, model loading). If an
auth-related dependency is inadvertently memoized at the wrong scope,
the first request's identity propagates to all subsequent requests
hitting the same worker process. The error is silent: the test suite
passes (one request, one identity), production fails (many requests,
same memoized identity).
Separately, `dependency_overrides` -- FastAPI's testing affordance
that replaces a dependency for a test run -- is a global mutation on
the app's DI registry. A test that forgets to clean up its override
leaves the override in place for every later test in the session, so
those tests exercise a fake identity instead of the real auth check.
---
## Pattern 1 -- Declare auth as a `Depends` on every protected route, never via middleware-only
```python
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class User(BaseModel):
id: str
email: str
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
"""Verify the token and return the authenticated user.
Returns a fresh User instance per request -- the function body
runs on each request, so no cross-request identity leakage.
"""
user = await verify_token_against_session_store(token)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid or expired token",
)
return user
@app.get("/profile")
async def read_profile(current_user: User = Depends(get_current_user)) -> dict:
# current_user is the per-request authenticated identity, typed
# and visible in the handler signature -- a reviewer sees the auth
# requirement directly without reading middleware config.
return {"id": current_user.id, "email": current_user.email}
```
The auth requirement appears in the route signature. A new route that
omits `Depends(get_current_user)` is immediately reviewable as
unauthenticated -- there's no hidden middleware behavior masking the
absence.
For broad-application auth requirements (e.g., every route under
`/admin/**` requires admin role), use a `dependencies=` list on a
sub-router or `APIRouter` so the dependency is still visible at the
route-group level:
```python
from fastapi import APIRouter, Depends
from .auth import require_admin
admin_router = APIRouter(
prefix="/admin",
dependencies=[Depends(require_admin)], # applies to every route under /admin
tags=["admin"],
)
```
---
## Pattern 2 -- Scope expensive-to-construct dependencies correctly
```python
from functools import lru_cache
from fastapi import Depends
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env")
database_url: str
api_key: str
feature_flags: dict[str, bool] = {}
@lru_cache(maxsize=1)
def get_settings() -> Settings:
"""Settings are app-wide and immutable -- safe to memoize."""
return Settings()
# In a route:From MILTONADINA/DevOPs, MIT.
More from MILTONADINA/DevOPs
- 0.565score
cost-attribution
MILTONADINA
Track per-client and per-feature LLM and cloud spend with cryptographic audit trail.
SkillAFreshness: AClaude Code +9 - 0.565score
proof-of-work
MILTONADINA
Produce structured proof artifacts for every completed claim.
SkillAFreshness: AClaude Code +9 - 0.565score
plan-decomposition
MILTONADINA
Break an approved spec into atomic, ordered, verifiable tasks before any code is written.
SkillAFreshness: AClaude Code +9 - 0.565score
multi-tool-failover
MILTONADINA
Manage session continuity when switching between Claude Code, Codex CLI, Cursor, Antigravity, Kiro, or local LLMs (OpenCode, Aider).
SkillAFreshness: AClaude Code +9 - 0.565score
goal-loop
MILTONADINA
Execute the spec-tests-implement-verify cycle for one atomic task at a time.
SkillAFreshness: AClaude Code +9 - 0.565score
baton-handoff
MILTONADINA
Write a complete handoff document at session end so the next agent (Claude Code, Codex, Cursor, Antigravity, Kiro, or local LLM) resumes exactly where this…
SkillAFreshness: AClaude Code +9 - 0.565score
observability-instrument
MILTONADINA
Add OpenTelemetry spans with user_id and tenant_id in baggage to any new code path that handles requests, runs agents, or performs billable operations.
SkillAFreshness: AClaude Code +9 - 0.565score
ears-spec-writing
MILTONADINA
Write requirement specifications in EARS (Easy Approach to Requirements Syntax) notation.
SkillAFreshness: AClaude Code +9 - 0.565score
openapi-first
MILTONADINA
Generate API code, types, validators, mock servers, and client SDKs from a single OpenAPI 3.1 specification.
SkillAFreshness: AClaude Code +9 - 0.561score
session-summary
MILTONADINA
Generate the end-of-session human-reviewable report.
SkillAFreshness: AClaude Code +9 - 0.561score
coppa-audit
MILTONADINA
Audit code, data flows, and UI for COPPA (Children's Online Privacy Protection Act) compliance.
SkillAFreshness: AClaude Code +9 - 0.560score
supabase-rpc-functions
MILTONADINA
Supabase RPC function security patterns -- SECURITY DEFINER with `SET search_path` discipline, `REVOKE EXECUTE FROM public` for least-privilege exposure…
SkillAFreshness: AClaude Code +9
Signals
- Stars
- 0
- Forks
- 0
- Open issues
- 12
- Last commit (this folder)
- Sep 25, 2026 (1 month ago)
- Last release
- Sep 23, 2026 (1 month ago)
From GitHub (fetched Oct 24, 2026).
Details
- License
- MIT
- Repository
- github.com/MILTONADINA/DevOPs
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from MILTONADINA
- 0.565score
baton-handoff
MILTONADINA
Write a complete handoff document at session end so the next agent (Claude Code, Codex, Cursor, Antigravity, Kiro, or local LLM) resumes exactly where this…
SkillAFreshness: AClaude Code +9 - 0.565score
observability-instrument
MILTONADINA
Add OpenTelemetry spans with user_id and tenant_id in baggage to any new code path that handles requests, runs agents, or performs billable operations.
SkillAFreshness: AClaude Code +9 - 0.565score
openapi-first
MILTONADINA
Generate API code, types, validators, mock servers, and client SDKs from a single OpenAPI 3.1 specification.
SkillAFreshness: AClaude Code +9 - 0.565score
ears-spec-writing
MILTONADINA
Write requirement specifications in EARS (Easy Approach to Requirements Syntax) notation.
SkillAFreshness: AClaude Code +9 - 0.565score
cost-attribution
MILTONADINA
Track per-client and per-feature LLM and cloud spend with cryptographic audit trail.
SkillAFreshness: AClaude Code +9 - 0.565score
goal-loop
MILTONADINA
Execute the spec-tests-implement-verify cycle for one atomic task at a time.
SkillAFreshness: AClaude Code +9
Cite this page
fastapi-dependency-injection skill. Agent Mart. https://agentmart.dev/skills/miltonadina-fastapi-dependency-injection (last updated 2026-10-24)