Write a CLAUDE.md for FastAPI with sections on Stack, Router Design, Dependency Injection, and Prohibitions. Keep it under 50 lines. Use positive patterns with code snippets. Place in repo root. Team-review changes as IaC.
Key Takeaways
- Write a CLAUDE.md for FastAPI with sections on Stack, Router Design, Dependency Injection, and Prohibitions.
- Keep it under 50 lines.
- Use positive patterns with code snippets.
- Team-review changes as IaC.
What Changed — The Specific Update
FastAPI developers using Claude Code have long faced a frustrating problem: the AI agent generates endpoints with inconsistent structures, varying dependency injection patterns, and scattered error handling. The solution isn't a new model update—it's a well-crafted CLAUDE.md file.
This article provides a production-tested CLAUDE.md template for FastAPI projects, based on real-world usage patterns from the community. The file acts as a system prompt for Claude Code, enforcing consistent code generation across your entire repository.
What It Means For You
Without a CLAUDE.md, Claude Code generates FastAPI code that varies with each session. One endpoint might use SessionLocal(), another uses Depends(get_db). One route uses response_model, another doesn't. This inconsistency creates technical debt and review overhead.
With a properly structured CLAUDE.md, Claude Code generates code that follows your team's conventions every time. The agent reads the file at project root and treats it as persistent instructions.
Key benefits:
-
Consistent router patterns: Every endpoint uses
APIRouter(prefix="/v1/xxx", tags=["xxx"]) -
Uniform dependency injection: All DB sessions use
Annotated[AsyncSession, Depends(get_db)] -
Standardized error handling: Business errors follow
HTTPException(status_code=422, ...)format -
No global state: Prohibits
db = SessionLocal()globally
Try It Now — The FastAPI CLAUDE.md Template
Create a CLAUDE.md file in your repository root with this content:
# Project Rules
## Stack
- Python 3.12 / FastAPI 0.115 / SQLAlchemy 2.x (async)
- Pydantic v2. BaseModel must include `model_config = ConfigDict(from_attributes=True)`
## Router Design
- One file per router. Use `router = APIRouter(prefix="/v1/xxx", tags=["xxx"])`
- Endpoint function names follow `verb_noun` pattern (e.g., `create_user`, `list_orders`)
## Dependency Injection
- DB sessions must use `Annotated[AsyncSession, Depends(get_db)]`
- Authentication uses `CurrentUser = Annotated[User, Depends(get_current_user)]`
## Prohibitions
- No global `db = SessionLocal()`
- Never omit `response_model` — always specify a schema
- No `print()` debugging — use `logger.info()`
## Testing
- Use pytest + httpx.AsyncClient
- Centralize fixtures in `tests/conftest.py`
- Mock only external HTTP calls; use SQLite in-memory for DB
## Error Handling
- Business errors: `raise HTTPException(status_code=422, detail={"code": "...", "message": "..."})`
- Let 500 errors propagate to middleware — never swallow them in endpoints
Pro tip: Keep this file under 50 lines. Claude Code's context window is finite—too many rules and the agent may skip them. Prioritize the most impactful patterns.
Multi-Tool Strategy
If your team also uses Cursor or OpenAI Codex, maintain CLAUDE.md as the source of truth and create symlinks:
ln -s CLAUDE.md .cursorrules
This keeps one canonical ruleset across tools. Cursor reads .cursorrules from root only; Claude Code supports hierarchical CLAUDE.md files in subdirectories.
Two Critical Rules for Effective CLAUDE.md
-
Write positive patterns, not prohibitions
- Bad: "Don't use
print()" - Good: "Use
logger.info()for debugging" - Agents follow "do this" instructions more reliably than "don't do that"
- Bad: "Don't use
-
Include concrete code snippets
- Instead of "use dependency injection", show
Annotated[AsyncSession, Depends(get_db)] - Snippets anchor the agent's generation to your exact syntax
- Instead of "use dependency injection", show
Team Workflow
Treat CLAUDE.md as infrastructure-as-code. Changes should go through PR review, just like Dockerfile or docker-compose.yml. This allows the team to:
- Review how agent behavior will change
- Catch contradictions (e.g., one rule says async, another implies sync)
- Document why patterns were chosen
The Result
After implementing this CLAUDE.md, one developer reported that Claude Code generated endpoints with identical structure across 20+ files, eliminating the "every endpoint looks different" problem. The agent consistently applied dependency injection patterns, response model declarations, and error handling formats without prompting.
FastAPI's convention-heavy design makes it especially suited for rule-file-driven development. The framework already expects patterns—the CLAUDE.md just ensures the AI applies them consistently.
Source: dev.to
Originally published on gentic.news
Top comments (0)