.cursorrules (deprecated)
rules/python-fastapi/.cursorrules.cursorrules
Quality
99/100
Scores the file, not the repository.Length
1,005 words
12 headings · 1 code blocksRepository
16
— · pushed 109 days agoLast changed
2 days ago
First indexed 2 days ago.1# Python FastAPI with Pydantic v2 — Cursor Rules23You are an expert Python developer building APIs with FastAPI and Pydantic v2, using async patterns throughout.45## Code Style67- 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.1617## FastAPI Patterns1819- 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.2728## Pydantic v2 Models2930- 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()`.3940## Async Patterns4142- 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.4950## Dependency Injection5152- 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.5960## Error Handling6162- 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.6970## Database (SQLAlchemy Async)7172- 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.7879## Testing8081- 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_*`.8889## File Structure9091```92app/93 main.py — FastAPI app instance, middleware, startup/shutdown94 config.py — Settings with pydantic-settings (BaseSettings)95 deps.py — Global dependencies (DB session, auth)96 routers/97 users.py — User endpoints98 items.py — Item endpoints99 models/100 user.py — SQLAlchemy ORM models101 item.py102 schemas/103 user.py — Pydantic request/response schemas104 item.py105 services/106 user_service.py — Business logic layer107 repositories/108 user_repo.py — Database access layer109 middleware/110 logging.py111 cors.py112 utils/113 security.py — Password hashing, JWT114 pagination.py — Pagination helpers115tests/116 conftest.py117 test_users.py118 test_items.py119alembic/120 versions/121```122123## Security124125- 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.133134## Performance135136- 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
Also in survivorforge/cursor-rules
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| survivorforge/cursor-rulesrules/ai-ml-python/.cursorrules · 16 | .cursorrules | teststylearchdeployment+2 | 81/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/api-design-rest/.cursorrules · 16 | .cursorrules | lint-formatstylesecurityapi+3 | 69/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/api-microservices/.cursorrules · 16 | .cursorrules | buildteststylearch+5 | 92/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/aws-serverless/.cursorrules · 16 | .cursorrules | teststylearchtypes+6 | 73/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/chrome-extension/.cursorrules · 16 | .cursorrules | teststylearchtesting-strategy+4 | 81/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/clean-code/.cursorrules · 16 | .cursorrules | styledo-notagent-behaviourdocs | 57/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/database-sql/.cursorrules · 16 | .cursorrules | styletypessecuritydatabase+3 | 65/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/devops-docker/.cursorrules · 16 | .cursorrules | setupbuildteststyle+4 | 93/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/devops-infrastructure/.cursorrules · 16 | .cursorrules | buildteststylesecurity+3 | 93/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/django-rest/.cursorrules · 16 | .cursorrules | buildteststylearch+5 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/docker-devops/.cursorrules · 16 | .cursorrules | setupteststylearch+6 | 85/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/flutter-dart/.cursorrules · 16 | .cursorrules | teststylearchtypes+5 | 89/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/fullstack-nextjs-prisma/.cursorrules · 16 | .cursorrules | teststylearchtypes+7 | 96/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/go-gin/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+5 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/go-production/.cursorrules · 16 | .cursorrules | teststylearchtesting-strategy+3 | 89/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/golang-api/.cursorrules · 16 | .cursorrules | buildteststylearch+6 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/langchain-ai/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+4 | 84/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/mcp-server/.cursorrules · 16 | .cursorrules | testlint-formatstylearch+7 | 68/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/mern-stack/.cursorrules · 16 | .cursorrules | setupteststylearch+6 | 81/100 | 2 days ago | |
| survivorforge/cursor-rulesrules/mobile-react-native/.cursorrules · 16 | .cursorrules | teststylearchtypes+7 | 89/100 | 2 days ago |
Diff against rules/ai-ml-python/.cursorrules Diff against rules/api-design-rest/.cursorrules Diff against rules/api-microservices/.cursorrules Diff against rules/aws-serverless/.cursorrules Diff against rules/chrome-extension/.cursorrules Diff against rules/clean-code/.cursorrules Diff against rules/database-sql/.cursorrules Diff against rules/devops-docker/.cursorrules Diff against rules/devops-infrastructure/.cursorrules Diff against rules/django-rest/.cursorrules Diff against rules/docker-devops/.cursorrules Diff against rules/flutter-dart/.cursorrules Diff against rules/fullstack-nextjs-prisma/.cursorrules Diff against rules/go-gin/.cursorrules Diff against rules/go-production/.cursorrules Diff against rules/golang-api/.cursorrules Diff against rules/langchain-ai/.cursorrules Diff against rules/mcp-server/.cursorrules Diff against rules/mern-stack/.cursorrules Diff against rules/mobile-react-native/.cursorrules
