Cursor Rules: FastAPI Clean Architecture & TDD Repository Pattern
Enforce strict Clean Architecture layers in Cursor: Domain Entities β Use Case Interactors β Repository Interfaces β FastAPI Route Controllers.
Parametric Customizer & Compiler Live Tool
Adjust the variables below. The prompt code and API payload update dynamically in real time.
Core feature or bounded context
# .cursorrules - FastAPI Production Clean Architecture Specification
You are an expert Python Staff Backend Engineer. When writing code, generating refactors, or creating test suites for this FastAPI project, enforce the following invariants strictly:
### 1. DIRECTORY STRUCTURE & SEPARATION OF CONCERNS
```
src/
βββ domain/ # Pure Python dataclasses, business rules, exceptions (ZERO external dependencies)
βββ application/ # Use case orchestrators, service interactors, DTOs
βββ infrastructure/ # SQLAlchemy 2.0 Async Session models, Redis caching, third-party clients
βββ presentation/ # FastAPI APIRouters, request schemas (Pydantic v2), response formatting
```
### 2. STRICT ARCHITECTURAL CONSTRAINTS
- **Domain Isolation**: Code in `domain/` must NEVER import from `fastapi`, `sqlalchemy`, or `pydantic`. It contains pure business entities.
- **Database Layer**: Use SQLAlchemy 2.0 `AsyncSession` with `select()` syntax only. Never use legacy query syntax (`session.query()`).
- **Dependency Injection**: Route handlers must declare dependencies via `Annotated[Service, Depends(get_service)]`.
- **Async Hygiene**: All I/O operations (Postgres queries, Redis calls, HTTP requests via `httpx.AsyncClient`) must be properly awaited.
- **Validation**: All input/output schemas must use Pydantic v2 `BaseModel` with strict typing (`model_config = ConfigDict(strict=True)`).
### 3. TEST-DRIVEN DEVELOPMENT (TDD) MANDATE
- For every new endpoint or use case, generate the corresponding `pytest` test suite first.
- Use `pytest-asyncio` with `asyncio_mode = auto`.
- Mock repository interfaces using pure in-memory fakes rather than patching raw database queries.
Target Domain Module:
{Subscription Billing & Multi-Tenant Metering Service}
Database Engine & ORM:
{PostgreSQL with asyncpg & SQLAlchemy 2.0 Async} Supercharge your FastAPI development with strict clean architecture .cursorrules.
Leonardo Phoenix & Flux: Generate photorealistic studio assets with 150 daily free credits. Zero setup required.
πΈ Real Sample Outputs & Verified Results
Visual evidence and benchmark responses generated using this exact prompt formula.
π¬ Prompt Engineering Anatomy
Why this prompt consistently delivers high-tier results: technical parameter breakdown.
Domain Independence Token Guarantees business logic remains 100% decoupled from web frameworks and database drivers.
Repository Fake Testing Enforces testing with fast in-memory dictionary repositories rather than spinning up slow Docker containers for unit tests.
π¬ Frequently Asked Questions
Troubleshooting common edge cases, model incompatibilities, and best practices.
How do I install these rules into my Cursor editor?
Copy this entire prompt and paste it into a file named .cursorrules at the root of your project repository.
Does this work with FastAPI 0.110+ and Pydantic v2?
Yes, it specifically enforces Pydantic v2 syntax, ConfigDict, and modern FastAPI Annotated dependency injection.
Cursor AI & Claude 3.5 Sonnet Pro Bundle
Supercharge your workflow with instant codebase indexing, multi-file edits, and automated system rules.
Explore Related Coding & Architecture Prompts View all β
Claude 3.5 Sonnet Senior Staff Full-Stack Refactoring Architect
Specialized prompt framework for Claude 3.5 Sonnet and Claude 3.7. Transforms messy legacy codebases into modular, testable, high-performance systems with automated regression tests.
cursorCursor AI (.cursorrules) for Next.js 15, React 19 & Tailwind CSS
Stops Cursor from writing outdated Next.js 13 patterns, Pages Router syntax, or deprecated React hooks. Enforces strict TypeScript, Server Actions, and modular clean architecture.
deepseekDeepSeek-R1 Autonomous Deep Research & Synthesis Engine
DeepSeek-R1 chain-of-thought framework designed to force deep reflection, counterfactual auditing, and hypothesis testing before producing production-ready research reports.