The Complete Production SOP: How to Deploy and Run FastAPI Dependency Injection & Security OAuth2 Schemes in Autonomous AI Agents
Production SOP for FastAPI dependency injection and OAuth2PasswordBearer schemes in Codex, Claude Code, and Cursor. Includes verified code and test overrides.
Technical Overview & Architectural Context
Without explicit procedural boundaries, autonomous coding agents frequently introduce critical architecture and security anti-patterns into FastAPI projects. Common agent hallucinations include creating unclosed database sessions inside route handlers, re-instantiating OAuth2 schemes inside local helper functions, directly accessing raw request authorization headers instead of using Depends(), and failing to structure dependencies hierarchically. These deviations lead to resource leaks (such as database connection exhaustion in high-concurrency environments), broken OpenAPI schema generation, and untestable codebases that cannot leverage app.dependency_overrides in isolated pytest suites. The 'FastAPI Dependency Injection & Security OAuth2 Schemes' skill forces deterministic boundaries on LLM agents across Codex, Claude Code, Cursor, and Windsurf. By enforcing yield generator patterns for async database sessions, standardized OAuth2PasswordBearer token extractors, and modular dependency composition (e.g., passing DB sessions directly into user resolution chains), the skill ensures that all generated Python code adheres strictly to FastAPI idioms, maintains a clean security perimeter, and supports seamless testing with 100% mocked isolation.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into your agent runtime.
Autonomous coding assistants inspect the workspace or global agent directories for procedural skill definitions. By mounting the SKILL.md file into the expected runtime directory (.agents/skills/fastapi-dependency-injection-security for Claude Code and Codex, or .cursor/skills for Cursor), the agent automatically registers triggers such as 'fastapi dependency injection depends' and 'oauth2passwordbearer fastapi'. This ensures that whenever backend route scaffolding or authentication is requested, the agent enforces secure architectural standards rather than ad-hoc implementations.
mkdir -p ~/.agents/skills/fastapi-dependency-injection-security && curl -fsSL https://askills.dev/api/skills/fastapi-dependency-injection-security/raw -o ~/.agents/skills/fastapi-dependency-injection-security/SKILL.md---
name: "fastapi-dependency-injection-security"
description: "Build modular, secure FastAPI endpoints using Depends() and OAuth2 password bearer schemes."
metadata:
author: "Tiangolo"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "fastapi dependency injection depends"
- "oauth2passwordbearer fastapi"
- "database session dependency fastapi"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---Mount the skill globally in ~/.agents/skills/ so all your workspace repositories inherit FastAPI dependency injection guardrails without duplicating configuration files.
Ensure that the agent sandbox has workspace write permissions enabled; otherwise, the agent will simulate creating the dependency modules without persisting them to disk.
Dependencies & Core Dependency Tree Implementation
Define session generators and hierarchical OAuth2 dependencies using yield and Depends().
Instruct the agent to generate app/core/deps.py containing the two foundational dependencies: the async database session lifecycle generator and the OAuth2 token validation sequence. In this pattern, get_db() safely yields a connection and guarantees session closure via context manager, while get_current_user resolves both the token (via OAuth2PasswordBearer) and the database session dependency (via Depends(get_db)).
uv add fastapi uvicorn sqlalchemy asyncpg pyjwt passlib[bcrypt]from typing import AsyncGenerator
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
import jwt
SECRET_KEY = "CHANGE_THIS_IN_PROD_USE_ENV_VAR"
ALGORITHM = "HS256"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/token")
engine = create_async_engine("sqlite+aiosqlite:///./test.db", echo=False)
SessionLocal = async_sessionmaker(autocommit=False, autoflush=False, bind=engine, class_=AsyncSession)
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
try:
yield session
finally:
await session.close()
async def get_current_user(token: str = Depends(oauth2_scheme), db: AsyncSession = Depends(get_db)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
user_id: str = payload.get("sub")
if user_id is None:
raise credentials_exception
except jwt.PyJWTError:
raise credentials_exception
# In production, query user from db: user = await db.get(User, user_id)
return {"user_id": user_id, "role": payload.get("role", "user")}Never instantiate OAuth2PasswordBearer inside route functions. Keep it as a module-level singleton so OpenAPI schema generators correctly extract the OAuth2 specification.
Avoid using bare yield statements without try...finally blocks or async context managers; unhandled client disconnects can leave async transactions open.
Endpoint Attachment and Route Composition
Protect API endpoints by attaching Depends() chains to route handler arguments.
Once dependencies are defined, endpoints declare required entities directly in their function signatures. The FastAPI DI resolution container inspects type hints, runs the dependencies concurrently when appropriate, injects resolved entities into the handler, and gracefully handles dependency tear-down after the response is dispatched.
from fastapi import APIRouter, Depends
from app.core.deps import get_current_user
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/me")
async def read_current_user(current_user: dict = Depends(get_current_user)):
"""Retrieve the profile of the currently authenticated user."""
return {"status": "success", "data": current_user}
@router.get("/admin/dashboard")
async def read_admin_dashboard(current_user: dict = Depends(get_current_user)):
"""Endpoint restricted by role evaluation derived from injected user."""
if current_user.get("role") != "admin":
from fastapi import HTTPException, status
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient permissions")
return {"status": "authorized", "metrics": {"active_nodes": 42}}For dependencies that only perform side-effects (like permission checks or rate limits), pass them into dependencies=[Depends(check_permission)] inside the APIRouter declaration to keep function signatures lean.
Do not pass callable functions directly without Depends(); omitting Depends() causes FastAPI to treat your dependency as a query parameter.
Verification, Mock Overrides & Output Quality Gate
Execute automated self-healing checks and isolated pytest verification using app.dependency_overrides.
A primary benefit of the FastAPI DI system is testability. Rather than mocking complex database drivers or authorization servers, test suites override dependencies using app.dependency_overrides. The skill requires the agent to generate and run an isolated test suite confirming both authenticated execution and mock dependency injection.
pytest tests/ -vimport pytest
from httpx import AsyncClient, ASGITransport
from fastapi import FastAPI
from app.core.deps import get_current_user
from app.api.v1.routes import router
app = FastAPI()
app.include_router(router)
@pytest.mark.asyncio
async def test_read_current_user_override():
mock_user = {"user_id": "usr_mock_123", "role": "admin"}
app.dependency_overrides[get_current_user] = lambda: mock_user
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.get("/users/me")
assert response.status_code == 200
assert response.json() == {"status": "success", "data": mock_user}
app.dependency_overrides.clear()Always clear app.dependency_overrides in a teardown fixture or immediately after the test assertion to prevent state leakage into adjacent unit tests.
If using ASGITransport with httpx, ensure pytest-asyncio is installed and configured with asyncio_mode = auto in pyproject.toml.
Real-World Scenario: Secure Multi-Tenant Customer API with Scoped Role Verification
“Scaffold a FastAPI user profile route /api/v1/customer/profile using Depends() and OAuth2PasswordBearer. Ensure that database sessions use an async generator dependency with yield and that auth token extraction validates JWT signatures. Provide a pytest test using app.dependency_overrides.”
Runtime Troubleshooting & Failure Modes
Root Cause: The route handler defined a database parameter without wrapping the dependency in Depends(), causing FastAPI to infer the parameter as a query or body payload schema.
# Replace:
async def read_items(db = get_db):
# With:
async def read_items(db: AsyncSession = Depends(get_db)):Root Cause: The async session generator dependency in get_db did not yield an active transaction or yielded multiple times in a single request lifecycle.
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with SessionLocal() as session:
yield sessionFrequently Asked Questions (FastAPI Dependency Injection & Security OAuth2 Schemes SOP)
Q:Can I use FastAPI Dependency Injection & Security OAuth2 Schemes across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. Symlinking or copying the manifest into your runtime configuration (~/.agents/skills or .cursor/skills) enables seamless, identical procedural execution across Codex, Claude Code, Cursor, and Windsurf.
Q:How does FastAPI Dependency Injection & Security OAuth2 Schemes prevent context window overflow during long agent sessions?
The skill encapsulates strict, modular dependency templates and verification gates. By instructing the agent to adhere to standard factory patterns (Depends(get_db), Depends(get_current_user)) and isolate tests via app.dependency_overrides, it eliminates repetitive boilerplate discussions and prevents the agent from re-architecting authentication systems mid-session.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100. It requires only standard workspace file access (fs_read: true, fs_write: workspace) to construct module files and run test suites, with shell_exec and net_access disabled by default.
Ready to equip your autonomous agent with FastAPI Dependency Injection & Security OAuth2 Schemes?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.