Cursor Rules Template: FastAPI + Strawberry GraphQL
Cursor Rules Template for FastAPI + Strawberry GraphQL stack to guide AI-assisted development.
Target User
Developers building FastAPI + Strawberry GraphQL backends who want Cursor AI rules
Use Cases
- Define GraphQL schema with Strawberry on FastAPI
- Enforce authentication using JWT with FastAPI
- Use async SQLAlchemy for PostgreSQL
- Test GraphQL resolvers with pytest and httpx
- Linting and pre-commit checks for code quality
- Limit GraphQL query depth and complexity
Markdown Template
Cursor Rules Template: FastAPI + Strawberry GraphQL
Overview
\nThis Cursor Rules configuration targets a FastAPI + Strawberry GraphQL stack. It codifies how Cursor AI should operate when assisting development of an asynchronous Python API server that serves a GraphQL endpoint implemented with Strawberry, backed by a PostgreSQL database via SQLAlchemy. The rules define the framework context, security expectations, testing workflows, and recommended project structure to keep the codebase production-ready.
\nWhen to Use These Cursor Rules
\n\n - Starting a new FastAPI + Strawberry GraphQL project with clear architectural boundaries.
\n - Onboarding teammates to a GraphQL backend with consistent coding standards and security practices.
\n - Maintaining a production-ready GraphQL API with robust testing, linting, and CI checks.
\n - Enforcing safe AI-assisted code generation for resolvers, mutations, and schema wiring.
\n\nCopyable .cursorrules Configuration
\n# Cursor Rules: FastAPI + Strawberry GraphQL (Cursor AI)\n# Architecture: production-grade, async Python backend\n\n# 1. Framework Role & Context\nframework: FastAPI\nstacks: ["FastAPI","Strawberry GraphQL"]\nlanguage: Python\ncontext: You are a coding assistant that designs, reviews, and refactors a FastAPI + Strawberry GraphQL backend for production, with a PostgreSQL database via async SQLAlchemy.\n\n# 2. Code Style and Style Guides\nstyle: PEP8, Black, isort, mypy, flake8\ntyping: strict\nformatting: Black\nlinting: flake8, ruff\n\n# 3. Architecture & Directory Rules\ndirectories:\n - app/\n - app/api/ v1/\n - app/graphql/\n - app/models/\n - app/db/\n - app/core/\n - app/tests/\n\n# 4. Authentication & Security Rules\nauth: JWT-OAuth2\nsecurity:\n - Use OAuth2PasswordBearer with JWT tokens\n - Passwords hashed with bcrypt\n - Secrets provided via environment, not in code\n - CSRF protection for state-changing requests? Use: False in GraphQL; rely on JWT validity\n\n# 5. Database and ORM patterns\ndb: async SQLAlchemy 2.0\ndb_config: {"DATABASE_URL":"postgresql+asyncpg://user:pass@localhost/db"}\nmodels: ["User","Post"]\nconsistency: eventual_with_checks\n\n# 6. Testing & Linting Workflows\ntests: pytest, httpx for integration tests\nci: pytest --maxfail=1 --disable-warnings -q\nprecommit: true\n\n# 7. Prohibited Actions and Anti-patterns for the AI\navoid: ["inline SQL strings without parameterization","exposing internal APIs in GraphQL schema","unbounded query depth","client-side authentication bypass"]\n\nRecommended Project Structure
\nfastapi-strawberry-graphql/\n├── app/\n│ ├── main.py\n│ ├── api/\n│ │ └── v1/\n│ │ ├── endpoints.py\n│ │ └── dependencies.py\n│ ├── graphql/\n│ │ ├── schema.py\n│ │ │ └── resolvers.py\n│ │ └── types.py\n│ ├── models/\n│ │ ├── user.py\n│ │ └── post.py\n│ ├── db/\n│ │ ├── base.py\n│ │ └── session.py\n│ ├── core/\n│ │ └── config.py\n│ └── services/\n│ └── auth.py\n├── tests/\n│ ├── conftest.py\n│ ├── test_endpoints.py\n│ └── test_graphql.py\n├── alembic.ini\n└── requirements.txt\n\nCore Engineering Principles
\n\n - Type safety and explicit contracts with Pydantic and type hints.
\n - Async I/O everywhere for database and HTTP operations.
\n - Single source of truth for user authentication and permissions.
\n - Idempotent GraphQL mutations with proper error handling.
\n - Secure by default: secrets, tokens, and encryption at rest in production.
\n - Observability: structured logging, tracing, and metrics.
\n\nCode Construction Rules
\n\n - Define GraphQL types with Strawberry using @type annotations and resolvers with clear input/output types.
\n - Use dependency injection in FastAPI for services and DB sessions.
\n - Validate inputs via Pydantic models and GraphQL input types; never trust client data.
\n - Architect resolvers to use repository pattern; avoid business logic in resolvers.
\n - Keep GraphQL schema in sync with database models; migrations must be explicit and tested.
\n - Do not embed raw SQL in resolvers; use parameterized queries via SQLAlchemy ORM.
\n\nSecurity and Production Rules
\n\n - Use JWT-based authentication with short-lived access tokens and refresh tokens when needed.
\n - Enforce role-based access at resolver level and with per-field permissions.
\n - Validate GraphQL depth and query complexity to prevent DoS attacks.
\n - Enable database connection pooling and TLS for PostgreSQL in prod.
\n - Keep secrets out of code; use environment-based configuration and secret managers.
\n\nTesting Checklist
\n\n - Unit tests for individual resolvers and services.
\n - Integration tests for GraphQL endpoints with a test database.
\n - End-to-end tests for authentication flows and GraphQL mutations.
\n - Static analysis: type checking, linting, and formatting in CI.
\n - Security tests: input validation, auth, and permissions checks.
\n\nCommon Mistakes to Avoid
\n\n - Ignoring GraphQL depth/complexity limits; allowlisting expensive operations.
\n - Overposting or leaking internal endpoints via GraphQL schema.
\n - Storing plaintext secrets or embedding credentials in code.
\n - Mixing business logic into GraphQL resolvers; keep concerns separated.
\n\nFAQ
\nHow do I integrate Cursor Rules with FastAPI and Strawberry?
\nUse this template as a blueprint for the final codebase. The rules enforce a clean architecture, proper authentication, and secure data handling while guiding AI-assisted resolver development. Implement the rules within your project root as a .cursorrules file and commit to CI tests to enforce compliance.
\nCan Cursor Rules template enforce GraphQL query depth and complexity?
\nYes. The rules include explicit guidance and code-level best practices to implement and enforce max query depth and complexity in Strawberry GraphQL, along with backend safeguards in FastAPI. This helps prevent DoS scenarios and keeps responses within reasonable resource limits.
\nWhat authentication mechanisms are recommended with this stack?
\nJWT-based authentication with OAuth2 is recommended for FastAPI backends. Store tokens securely, validate claims server-side, and implement per-resolver or per-field permission checks in Strawberry resolvers to enforce access control.
\nHow do I run tests for the GraphQL API?
\nRun unit tests for resolvers and services, followed by integration tests against a test database. Use pytest with httpx to exercise GraphQL endpoints, and ensure CI runs linting, type checks, and security tests on pull requests.
\nIs this template compatible with async SQLAlchemy and PostgreSQL?
\nYes. The template targets async SQLAlchemy 2.0 with PostgreSQL, including async sessions, migrations, and connection pooling. It emphasizes repository patterns and proper transaction handling to keep data integrity in async contexts.Overview
\nThis Cursor Rules configuration targets a FastAPI + Strawberry GraphQL stack. It codifies how Cursor AI should operate when assisting development of an asynchronous Python API server that serves a GraphQL endpoint implemented with Strawberry, backed by a PostgreSQL database via SQLAlchemy. The rules define the framework context, security expectations, testing workflows, and recommended project structure to keep the codebase production-ready.
\nWhen to Use These Cursor Rules
\n- \n
- Starting a new FastAPI + Strawberry GraphQL project with clear architectural boundaries. \n
- Onboarding teammates to a GraphQL backend with consistent coding standards and security practices. \n
- Maintaining a production-ready GraphQL API with robust testing, linting, and CI checks. \n
- Enforcing safe AI-assisted code generation for resolvers, mutations, and schema wiring. \n
Copyable .cursorrules Configuration
\n# Cursor Rules: FastAPI + Strawberry GraphQL (Cursor AI)\n# Architecture: production-grade, async Python backend\n\n# 1. Framework Role & Context\nframework: FastAPI\nstacks: ["FastAPI","Strawberry GraphQL"]\nlanguage: Python\ncontext: You are a coding assistant that designs, reviews, and refactors a FastAPI + Strawberry GraphQL backend for production, with a PostgreSQL database via async SQLAlchemy.\n\n# 2. Code Style and Style Guides\nstyle: PEP8, Black, isort, mypy, flake8\ntyping: strict\nformatting: Black\nlinting: flake8, ruff\n\n# 3. Architecture & Directory Rules\ndirectories:\n - app/\n - app/api/ v1/\n - app/graphql/\n - app/models/\n - app/db/\n - app/core/\n - app/tests/\n\n# 4. Authentication & Security Rules\nauth: JWT-OAuth2\nsecurity:\n - Use OAuth2PasswordBearer with JWT tokens\n - Passwords hashed with bcrypt\n - Secrets provided via environment, not in code\n - CSRF protection for state-changing requests? Use: False in GraphQL; rely on JWT validity\n\n# 5. Database and ORM patterns\ndb: async SQLAlchemy 2.0\ndb_config: {"DATABASE_URL":"postgresql+asyncpg://user:pass@localhost/db"}\nmodels: ["User","Post"]\nconsistency: eventual_with_checks\n\n# 6. Testing & Linting Workflows\ntests: pytest, httpx for integration tests\nci: pytest --maxfail=1 --disable-warnings -q\nprecommit: true\n\n# 7. Prohibited Actions and Anti-patterns for the AI\navoid: ["inline SQL strings without parameterization","exposing internal APIs in GraphQL schema","unbounded query depth","client-side authentication bypass"]\n\nRecommended Project Structure
\nfastapi-strawberry-graphql/\n├── app/\n│ ├── main.py\n│ ├── api/\n│ │ └── v1/\n│ │ ├── endpoints.py\n│ │ └── dependencies.py\n│ ├── graphql/\n│ │ ├── schema.py\n│ │ │ └── resolvers.py\n│ │ └── types.py\n│ ├── models/\n│ │ ├── user.py\n│ │ └── post.py\n│ ├── db/\n│ │ ├── base.py\n│ │ └── session.py\n│ ├── core/\n│ │ └── config.py\n│ └── services/\n│ └── auth.py\n├── tests/\n│ ├── conftest.py\n│ ├── test_endpoints.py\n│ └── test_graphql.py\n├── alembic.ini\n└── requirements.txt\n\nCore Engineering Principles
\n- \n
- Type safety and explicit contracts with Pydantic and type hints. \n
- Async I/O everywhere for database and HTTP operations. \n
- Single source of truth for user authentication and permissions. \n
- Idempotent GraphQL mutations with proper error handling. \n
- Secure by default: secrets, tokens, and encryption at rest in production. \n
- Observability: structured logging, tracing, and metrics. \n
Code Construction Rules
\n- \n
- Define GraphQL types with Strawberry using @type annotations and resolvers with clear input/output types. \n
- Use dependency injection in FastAPI for services and DB sessions. \n
- Validate inputs via Pydantic models and GraphQL input types; never trust client data. \n
- Architect resolvers to use repository pattern; avoid business logic in resolvers. \n
- Keep GraphQL schema in sync with database models; migrations must be explicit and tested. \n
- Do not embed raw SQL in resolvers; use parameterized queries via SQLAlchemy ORM. \n
Security and Production Rules
\n- \n
- Use JWT-based authentication with short-lived access tokens and refresh tokens when needed. \n
- Enforce role-based access at resolver level and with per-field permissions. \n
- Validate GraphQL depth and query complexity to prevent DoS attacks. \n
- Enable database connection pooling and TLS for PostgreSQL in prod. \n
- Keep secrets out of code; use environment-based configuration and secret managers. \n
Testing Checklist
\n- \n
- Unit tests for individual resolvers and services. \n
- Integration tests for GraphQL endpoints with a test database. \n
- End-to-end tests for authentication flows and GraphQL mutations. \n
- Static analysis: type checking, linting, and formatting in CI. \n
- Security tests: input validation, auth, and permissions checks. \n
Common Mistakes to Avoid
\n- \n
- Ignoring GraphQL depth/complexity limits; allowlisting expensive operations. \n
- Overposting or leaking internal endpoints via GraphQL schema. \n
- Storing plaintext secrets or embedding credentials in code. \n
- Mixing business logic into GraphQL resolvers; keep concerns separated. \n
FAQ
\nHow do I integrate Cursor Rules with FastAPI and Strawberry?
\nUse this template as a blueprint for the final codebase. The rules enforce a clean architecture, proper authentication, and secure data handling while guiding AI-assisted resolver development. Implement the rules within your project root as a .cursorrules file and commit to CI tests to enforce compliance.
\nCan Cursor Rules template enforce GraphQL query depth and complexity?
\nYes. The rules include explicit guidance and code-level best practices to implement and enforce max query depth and complexity in Strawberry GraphQL, along with backend safeguards in FastAPI. This helps prevent DoS scenarios and keeps responses within reasonable resource limits.
\nWhat authentication mechanisms are recommended with this stack?
\nJWT-based authentication with OAuth2 is recommended for FastAPI backends. Store tokens securely, validate claims server-side, and implement per-resolver or per-field permission checks in Strawberry resolvers to enforce access control.
\nHow do I run tests for the GraphQL API?
\nRun unit tests for resolvers and services, followed by integration tests against a test database. Use pytest with httpx to exercise GraphQL endpoints, and ensure CI runs linting, type checks, and security tests on pull requests.
\nIs this template compatible with async SQLAlchemy and PostgreSQL?
\nYes. The template targets async SQLAlchemy 2.0 with PostgreSQL, including async sessions, migrations, and connection pooling. It emphasizes repository patterns and proper transaction handling to keep data integrity in async contexts.