Skip to content
Agentmart
Submit a tool

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

IndexedMIT
Write a review

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.

We use your email only for this newsletter. Privacy

About

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.

Use cases: backend, security

No 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

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
First seen
Oct 24, 2026
Last checked
Oct 24, 2026

More from MILTONADINA

Cite this page

fastapi-dependency-injection skill. Agent Mart. https://agentmart.dev/skills/miltonadina-fastapi-dependency-injection (last updated 2026-10-24)