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 stack

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 stack
Framework: FastAPI
Stack: FastAPI, SQLModel, Alembic, PostgreSQL
ProjectRoot: /
Role: You are Cursor AI configured to assist with building production-grade backends using FastAPI, SQLModel (ORM), Alembic for migrations, and PostgreSQL. Prioritize security, testability, and clean architecture. When unsure, ask for clarification instead of guessing.
Context: The project lives at the repository root. Models reside in app/models.py. Migrations live under migrations/versions. The API surface is defined in app/api/. Use Alembic for migrations. Authentication uses OAuth2 with JWT. CI runs tests and linting on PRs.
CodeStyle: Black, isort, flake8; enforce type hints; format consistently; avoid wildcard imports; prefer explicit imports.
Architecture: 
- app/
  - __init__.py
  - main.py
  - models.py
  - api/v1/
  - core/config.py
  - db.py
- migrations/
  - versions/
- tests/
- alembic.ini
Authentication & Security: Use OAuth2PasswordBearer with JWT tokens. Store password hashes with bcrypt. Do not hardcode secrets; read from environment. Validate tokens on protected endpoints via FastAPI dependencies.
Database & ORM: SQLModel models in app/models.py. PostgreSQL as the database. Use Alembic for migrations, with autogenerate enabled. Use parameterized queries and avoid raw string interpolation to prevent SQL injection.
Testing & Linters: pytest for unit and integration tests; pytest-asyncio for async endpoints. Pre-commit hooks to run Black, isort, and flake8. Tests cover models, migrations, endpoints, and security flows.
Prohibited Actions & Anti-patterns: Do not run shell commands from AI output. Do not bypass migrations or skip Alembic; do not embed credentials in code; do not access production secrets in examples; do not generate code that exposes private data or insecure defaults.

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.