Real files, at real paths, counted every nightCounted 08:17 UTCDiff two files
7,205instruction files1,198repositories visited4,189rows written36files changed8formats20section tags85stacksCounted 13 September 2026
rules/python-fastapi/.cursorrulessurvivorforge/cursor-rules on mainOpen on GitHubsurvivorforgeRaw file7.5 kBDiff against another filePick the second file

.cursorrules in survivorforge/cursor-rules runs 1,005 words across 12 headings.

๐Ÿค– Curated collection of .cursorrules files for Cursor IDE โ€” boost your AI coding with framework-specific rules for React, Next.js, Python, Node.js, and more

No language published18 starsChanged 1 month ago7.5 kBNested, not at the root.cursorrules
Covers

10 of the 20 section tags

In the order a file is read in
Headings

12 headings, in the order the file writes them

01Python FastAPI with Pydantic v2 โ€” Cursor Rules
02Code Style
03FastAPI Patterns
04Pydantic v2 Models
05Async Patterns
06Dependency Injection
07Error Handling
08Database (SQLAlchemy Async)
09Testing
10File Structure
11Security
12Performance
Commands

3 commands this file writes down

Extracted from the file, verbatim
pytest
pytest-asyncio
python-jose
The file

rules/python-fastapi/.cursorrules

142 lines
1# Python FastAPI with Pydantic v2 โ€” Cursor Rules
2
3You are an expert Python developer building APIs with FastAPI and Pydantic v2, using async patterns throughout.
4
5## Code Style
6
7- Use Python 3.11+ features: `match` statements, `StrEnum`, `Self` type, exception groups.
8- Type-annotate every function signature โ€” parameters and return types. Never use `Any` unless interfacing with genuinely dynamic data.
9- Use `snake_case` for functions, variables, and modules. `PascalCase` for classes. `UPPER_SNAKE_CASE` for constants.
10- Prefer f-strings over `format()` or `%` formatting.
11- Line length: 88 characters (Black default). Use Black for formatting, Ruff for linting.
12- Import order: stdlib, third-party, local. Separate with blank lines. Use `isort` profile for Black.
13- Use `from __future__ import annotations` at the top of every file for forward reference support.
14- Prefer `pathlib.Path` over `os.path` for filesystem operations.
15- Use `dataclasses` for simple data containers without validation. Use Pydantic models when validation is needed.
16
17## FastAPI Patterns
18
19- Define routers in separate files, one per resource domain: `routers/users.py`, `routers/items.py`.
20- Use `APIRouter` with a prefix and tags: `router = APIRouter(prefix="/users", tags=["users"])`.
21- Use dependency injection for shared logic: database sessions, auth, pagination, rate limiting.
22- Prefer `async def` for all route handlers. Use `def` (sync) only for CPU-bound operations that can't be easily made async.
23- Return Pydantic response models explicitly: `@router.get("/users/{id}", response_model=UserOut)`.
24- Use `status_code` parameter: `@router.post("/users", status_code=status.HTTP_201_CREATED)`.
25- Use `HTTPException` for expected errors. Use exception handlers for unexpected errors.
26- Document all endpoints with docstrings โ€” they appear in the OpenAPI schema.
27
28## Pydantic v2 Models
29
30- Use Pydantic v2 syntax exclusively. Never use v1 deprecated patterns.
31- Use `model_validator(mode='before')` instead of deprecated `@validator`.
32- Use `field_validator` instead of `@validator` with `@classmethod`.
33- Use `model_config = ConfigDict(...)` instead of inner `class Config`.
34- Define separate models for input and output: `UserCreate`, `UserUpdate`, `UserOut`.
35- Use `Field()` for validation constraints: `Field(min_length=1, max_length=100, description="...")`.
36- Use `Annotated[int, Field(gt=0)]` pattern for reusable field types.
37- Prefer `Enum` or `Literal` types for fields with fixed allowed values.
38- Use `model_dump()` instead of deprecated `dict()`. Use `model_validate()` instead of `parse_obj()`.
39
40## Async Patterns
41
42- Use `asyncio` for I/O-bound operations: database queries, HTTP calls, file I/O.
43- Use `httpx.AsyncClient` for async HTTP requests, not `requests`.
44- Use `asyncio.gather()` for concurrent I/O operations when tasks are independent.
45- Never use blocking I/O (e.g., `open()`, `requests.get()`) inside async functions. Use `aiofiles` or `run_in_executor`.
46- For database access, use async drivers: `asyncpg` for PostgreSQL, `motor` for MongoDB, `aiosqlite` for SQLite.
47- Use `async for` with async iterators/generators for streaming responses.
48- Handle task cancellation gracefully with try/finally blocks.
49
50## Dependency Injection
51
52- Define dependencies as async functions that `yield` (for cleanup) or return values.
53- Use `Depends()` in route handler signatures for dependency injection.
54- Compose dependencies: a dependency can depend on other dependencies.
55- Use `Annotated` types for cleaner dependency signatures:
56 `CurrentUser = Annotated[User, Depends(get_current_user)]`
57- For database sessions, use a dependency that yields the session and closes it after the request.
58- Create a `deps.py` file in each router module for module-specific dependencies.
59
60## Error Handling
61
62- Raise `HTTPException` with appropriate status codes and descriptive detail messages.
63- Create custom exception classes for domain-specific errors. Map them to HTTP responses with exception handlers.
64- Use `@app.exception_handler(CustomError)` to centralize error response formatting.
65- Return consistent error response shapes: `{"detail": "message", "code": "ERROR_CODE"}`.
66- Log all 5xx errors with full context (request path, user, traceback). Never log sensitive data (passwords, tokens).
67- Use `try/except` with specific exception types. Never use bare `except:`.
68- For validation errors, let Pydantic/FastAPI handle them automatically โ€” they return 422 with detailed error info.
69
70## Database (SQLAlchemy Async)
71
72- Use SQLAlchemy 2.0 style with `select()`, `insert()`, `update()`, `delete()` statements.
73- Use `AsyncSession` from `sqlalchemy.ext.asyncio`. Never use synchronous sessions.
74- Define models in `models/` directory, one file per domain entity.
75- Use Alembic for migrations. Always create a migration for schema changes.
76- Use repository pattern: encapsulate database queries in repository classes or functions.
77- Prefer `selectinload` or `subqueryload` for eager loading relationships. Avoid N+1 queries.
78
79## Testing
80
81- Use `pytest` with `pytest-asyncio` for async test support.
82- Use `httpx.AsyncClient` with `ASGITransport` for testing FastAPI apps without starting a server.
83- Create a test database fixture that sets up and tears down the database per test session.
84- Use factories (with `factory_boy` or custom functions) for creating test data.
85- Test each endpoint: happy path, validation errors, auth errors, not found, edge cases.
86- Place tests in a `tests/` directory mirroring the source structure.
87- Name test files `test_*.py` and test functions `test_*`.
88
89## File Structure
90
91```
92app/
93 main.py โ€” FastAPI app instance, middleware, startup/shutdown
94 config.py โ€” Settings with pydantic-settings (BaseSettings)
95 deps.py โ€” Global dependencies (DB session, auth)
96 routers/
97 users.py โ€” User endpoints
98 items.py โ€” Item endpoints
99 models/
100 user.py โ€” SQLAlchemy ORM models
101 item.py
102 schemas/
103 user.py โ€” Pydantic request/response schemas
104 item.py
105 services/
106 user_service.py โ€” Business logic layer
107 repositories/
108 user_repo.py โ€” Database access layer
109 middleware/
110 logging.py
111 cors.py
112 utils/
113 security.py โ€” Password hashing, JWT
114 pagination.py โ€” Pagination helpers
115tests/
116 conftest.py
117 test_users.py
118 test_items.py
119alembic/
120 versions/
121```
122
123## Security
124
125- Use OAuth2 with JWT tokens for authentication. Use `python-jose` for JWT encoding/decoding.
126- Hash passwords with `bcrypt` via `passlib`. Never store plaintext passwords.
127- Validate and sanitize all input through Pydantic models โ€” do not trust raw request data.
128- Use CORS middleware with explicit allowed origins. Never use `allow_origins=["*"]` in production.
129- Rate limit sensitive endpoints (login, registration, password reset).
130- Use parameterized queries (SQLAlchemy handles this). Never concatenate user input into SQL strings.
131- Store secrets in environment variables. Use `pydantic-settings` with `.env` files for configuration.
132- Set secure headers: HSTS, X-Content-Type-Options, X-Frame-Options.
133
134## Performance
135
136- Use connection pooling for database connections (SQLAlchemy default with `create_async_engine`).
137- Use Redis for caching frequently accessed data. Use `aioredis` for async Redis access.
138- Implement pagination for all list endpoints. Default page size of 20-50 items.
139- Use background tasks (`BackgroundTasks`) for non-blocking operations like sending emails.
140- Profile slow endpoints with middleware that logs request duration.
141- Use streaming responses (`StreamingResponse`) for large file downloads.
142
The rest of the repository

survivorforge/cursor-rules ships 20 other instruction files

This listing

Whoever runs survivorforge/cursor-rules can claim it

This is yours? Claim this config and we will write to you when the measurement moves. The check is one token placed where only you can place it, and there is no account and no password.