Cursor Rules TemplatesCursor Rules Template

Cursor Rules Template: FastAPI, SQLModel, Alembic, PostgreSQL

Cursor Rules Template for a FastAPI stack using SQLModel, Alembic, and PostgreSQL. Copyable .cursorrules block plus stack-specific guidelines for secure, testable development.

.cursorrules templatecursor-rulesfastapisqlmodelalembicpostgresqlpythonbackendci/cdtestingCursor AI rules

Target User

Developers building production-grade backends with FastAPI, SQLModel, Alembic migrations, and PostgreSQL

Use Cases

  • API backend with Postgres data models
  • Database migrations and versioning with Alembic
  • Automated testing and linting pipelines
  • CI/CD integration for API services

Markdown Template

Cursor Rules Template: FastAPI, SQLModel, Alembic, PostgreSQL

# Cursor Rules for FastAPI + SQLModel + Alembic + PostgreSQL

Framework Role & Context
- You are Cursor AI configured to assist with a production-grade FastAPI backend using SQLModel, Alembic migrations, and PostgreSQL.
- Prioritize secure defaults, clean architecture, typed models, migration discipline, testability, and operational readiness.
- When requirements are ambiguous, ask for clarification before generating code that changes schemas, authentication, permissions, or production behavior.

Code Style and Style Guides
- Use modern Python with explicit type hints, clear imports, and predictable module boundaries.
- Format with Black and isort, lint with flake8 or Ruff, and keep exported functions and dependencies easy to test.
- Avoid wildcard imports, hidden side effects, global mutable state, and framework logic inside model definitions.

Architecture & Directory Rules
- Keep the application under app/ with clear boundaries between API routes, core config, database sessions, models, services, and tests.
- Use app/api/v1/ for versioned routers and keep route handlers thin.
- Keep SQLModel table definitions in app/models.py or a dedicated app/models/ package when the domain grows.
- Keep Alembic migration files under migrations/versions and never bypass migrations for schema changes.

Authentication & Security Rules
- Use OAuth2PasswordBearer or an equivalent FastAPI dependency for protected endpoints.
- Store password hashes with bcrypt or Argon2; never store plaintext passwords.
- Read secrets, token settings, database URLs, and allowed origins from environment-backed settings.
- Validate tokens through FastAPI dependencies before protected route logic runs.
- Never hardcode production credentials, JWT secrets, API keys, or database URLs in generated code.

Database and ORM Patterns
- Use SQLModel models for table definitions and typed application objects.
- Use PostgreSQL-specific behavior deliberately and document it when indexes, constraints, JSONB, or extensions are introduced.
- Use Alembic autogenerate carefully: review every migration before applying it.
- Use parameterized queries and SQLModel or SQLAlchemy expression APIs instead of string interpolation.
- Keep session lifecycle explicit through FastAPI dependencies and close sessions correctly.

Testing & Linting Workflows
- Use pytest for unit and integration tests, with a real test PostgreSQL database for migration and endpoint coverage when possible.
- Test models, CRUD behavior, migrations, auth dependencies, error handling, and representative API endpoints.
- CI should run formatting checks, linting, type checks where configured, migrations, and the test suite on every pull request.
- Use fixtures for deterministic test data and avoid tests that depend on production services or secrets.

Prohibited Actions and Anti-patterns for the AI
- Do not generate raw SQL with concatenated user input.
- Do not bypass Alembic migrations or edit production schema manually.
- Do not embed credentials, tokens, private URLs, or production secrets in examples.
- Do not disable authentication, authorization, validation, or security middleware for convenience.
- Do not generate code that exposes private data, stack traces, SQL errors, or internal infrastructure details in API responses.

Overview

Direct answer: This Cursor Rules Template provides a copyable .cursorrules configuration and stack-specific guidance for a production-grade backend using FastAPI, SQLModel, Alembic migrations, and PostgreSQL. It codifies conventions, safety rules, and testing expectations to help Cursor AI generate consistent, production-ready guidance and code.

Cursor rules configuration is a structured, repeatable way to encode stack-specific constraints for Cursor AI. This template targets FastAPI with SQLModel as the ORM, Alembic for migrations, and PostgreSQL as the database, emphasizing secure defaults, clean architecture, and testability.

When to Use These Cursor Rules

  • Starting a new FastAPI service that uses SQLModel for data models and PostgreSQL for storage.
  • Setting up Alembic-based migrations and a migration-driven development workflow.
  • Ensuring Cursor AI outputs align with a clean project structure, dependency injection, and secure authentication patterns.
  • Embedding tests and linting into CI/CD pipelines for backend services.

Copyable .cursorrules Configuration

# Cursor Rules for FastAPI + SQLModel + Alembic + PostgreSQL

Framework Role & Context
- You are Cursor AI configured to assist with a production-grade FastAPI backend using SQLModel, Alembic migrations, and PostgreSQL.
- Prioritize secure defaults, clean architecture, typed models, migration discipline, testability, and operational readiness.
- When requirements are ambiguous, ask for clarification before generating code that changes schemas, authentication, permissions, or production behavior.

Code Style and Style Guides
- Use modern Python with explicit type hints, clear imports, and predictable module boundaries.
- Format with Black and isort, lint with flake8 or Ruff, and keep exported functions and dependencies easy to test.
- Avoid wildcard imports, hidden side effects, global mutable state, and framework logic inside model definitions.

Architecture & Directory Rules
- Keep the application under app/ with clear boundaries between API routes, core config, database sessions, models, services, and tests.
- Use app/api/v1/ for versioned routers and keep route handlers thin.
- Keep SQLModel table definitions in app/models.py or a dedicated app/models/ package when the domain grows.
- Keep Alembic migration files under migrations/versions and never bypass migrations for schema changes.

Authentication & Security Rules
- Use OAuth2PasswordBearer or an equivalent FastAPI dependency for protected endpoints.
- Store password hashes with bcrypt or Argon2; never store plaintext passwords.
- Read secrets, token settings, database URLs, and allowed origins from environment-backed settings.
- Validate tokens through FastAPI dependencies before protected route logic runs.
- Never hardcode production credentials, JWT secrets, API keys, or database URLs in generated code.

Database and ORM Patterns
- Use SQLModel models for table definitions and typed application objects.
- Use PostgreSQL-specific behavior deliberately and document it when indexes, constraints, JSONB, or extensions are introduced.
- Use Alembic autogenerate carefully: review every migration before applying it.
- Use parameterized queries and SQLModel or SQLAlchemy expression APIs instead of string interpolation.
- Keep session lifecycle explicit through FastAPI dependencies and close sessions correctly.

Testing & Linting Workflows
- Use pytest for unit and integration tests, with a real test PostgreSQL database for migration and endpoint coverage when possible.
- Test models, CRUD behavior, migrations, auth dependencies, error handling, and representative API endpoints.
- CI should run formatting checks, linting, type checks where configured, migrations, and the test suite on every pull request.
- Use fixtures for deterministic test data and avoid tests that depend on production services or secrets.

Prohibited Actions and Anti-patterns for the AI
- Do not generate raw SQL with concatenated user input.
- Do not bypass Alembic migrations or edit production schema manually.
- Do not embed credentials, tokens, private URLs, or production secrets in examples.
- Do not disable authentication, authorization, validation, or security middleware for convenience.
- Do not generate code that exposes private data, stack traces, SQL errors, or internal infrastructure details in API responses.

Recommended Project Structure

fastapi-sqlmodel-alembic-postgresql-cursor-rules/
├── alembic.ini
├── migrations/
│   └── versions/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   ├── api/
│   │   └── v1/
│   │       └── endpoints.py
│   ├── core/
│   │   └── config.py
│   └── db.py
├── tests/
│   ├── test_models.py
│   └── test_endpoints.py
└── requirements.txt

Core Engineering Principles

  • Explicit architecture: clear separation of concerns between API, data models, and database access.
  • Security by default: avoid hardcoded credentials, implement robust auth, validate inputs, and limit permissions.
  • Testability: unit and integration tests with CI for every change.
  • Observability: structured logging, metrics, and tracing hooks for fast debugging in production.
  • Deterministic code generation: Cursor AI outputs are deterministic and auditable via the .cursorrules configuration.
  • Maintainable code style: adhere to Black/Isort, type hints, and clear naming conventions.

Code Construction Rules

  • Models must live in app/models.py using SQLModel; migrations managed by Alembic with autogenerate enabled.
  • Endpoints should use FastAPI routers with versioned paths (e.g., /api/v1/).
  • Use dependency injection for database sessions and current_user; avoid global mutable state.
  • All DB operations must be asynchronous if the driver supports it; otherwise use synchronous sessions with proper thread handling.
  • Authentication uses OAuth2 with JWT; access tokens are short-lived and refreshed securely.
  • Testing: unit tests for models, integration tests for endpoints; CI runs linting and tests on PRs.
  • Prohibited: Do not use raw SQL with string concatenation; do not bypass Alembic migrations; do not embed secrets; do not disable security middlewares in production.

Security and Production Rules

  • Store secrets in environment variables or secret managers; never commit credentials.
  • Use HTTPS in production and secure cookies for session tokens.
  • Validate input schemas strictly; enable CSRF protection where applicable for web-facing endpoints.
  • Limit database permissions to the minimum required for the service account.
  • Enable database auditing and query logging; monitor for long-running queries.

Testing Checklist

  • Unit tests for all SQLModel models with isolated in-memory databases where possible.
  • Integration tests for API endpoints; mock external services; use a test Postgres instance in CI.
  • Migration tests to verify Alembic upgrade/downgrade paths.
  • CI/CD: lint, tests, and type checks in PR pipelines; fail on any warning treated as error.

Common Mistakes to Avoid

  • Skipping Alembic migrations in new deployments or changing migrations manually.
  • Hardcoding secrets or credentials in code or migration scripts.
  • Using non-parameterized SQL queries, leading to SQL injection vectors.
  • Overusing global state or side effects in API endpoints.
  • Ignoring type hints and test coverage, leading to brittle code.

FAQ

What is this Cursor Rules Template for?

This template provides a ready-to-paste .cursorrules block and stack-specific guidance to build a production-grade FastAPI app with SQLModel, Alembic, and PostgreSQL. It codifies architecture, security, testing, and CI/CD practices so Cursor AI output stays aligned with the stack.

Where do I place the .cursorrules file?

Place the .cursorrules file at the project root. The rules reference the expected directory layout (app/models.py, migrations/, tests/, etc.) and guide Cursor AI in generating compatible code and recommendations.

How do I customize for my environment?

Update environment-specific settings (DATABASE_URL, secret keys, and migration strategies) via environment variables. Do not embed secrets in the .cursorrules block or generated code. Adapt endpoint paths and auth scopes to your deployment.

What should I verify in generated code?

Verify usage of SQLModel models in app/models.py, Alembic-driven migrations, JWT-based authentication, versioned API routes, and tests that cover models, endpoints, and migrations. Cursor AI should avoid unsafe patterns and reflect the documented rules.

Which security considerations are included?

Includes proper auth flow, secret management, input validation, and restricted database permissions. The template discourages insecure patterns such as embedding credentials or bypassing migrations, and it emphasizes secure defaults.

Related implementation resources: AI Use Case for Software Agencies Using Github Copilot To Accelerate Boilerplate Code Generation for New Client Mvps and Using Skill Files to Stop SQL Injection in Generated Backend Code.