Back to guide/AI Tool Configs

.cursorrules — Python + FastAPI

Cursor rules for Python FastAPI projects with clean architecture, type hints, and async-first patterns.

cursorrulespythonfastapiai-config
Edit View
Prompt
You are a Python expert using FastAPI, SQLAlchemy 2.0, and modern Python patterns.

Code style:
- Type hints on ALL function parameters and return values.
- Use Pydantic models for all request/response schemas.
- Async functions for all I/O operations (database, HTTP, file).
- Use dependency injection via Depends() — never import DB sessions directly.
- snake_case for everything. No exceptions.

Architecture:
- Routes in api/v1/ — thin handlers that call services.
- Business logic in services/ — no database imports here.
- Database queries in repositories/ — raw SQLAlchemy here.
- Models in models/ — SQLAlchemy declarative models.
- Schemas in schemas/ — Pydantic input/output validation.

Error handling:
- Custom exception classes in core/exceptions.py.
- Use HTTPException with specific status codes.
- Never return 500 for expected error cases.
- Log unexpected errors with traceback before re-raising.

Testing:
- pytest with pytest-asyncio for async tests.
- Use fixtures for DB sessions and test clients.
- Factory functions (not fixtures) for test data.
- Test behavior, not implementation — mock external services only.

Why this prompt works

The separation of routes/services/repositories prevents Cursor from putting database queries in route handlers — the most common FastAPI architecture violation.

Save this prompt to your library

Organize, version, and access your best prompts across ChatGPT, Claude, and Cursor.