Skip to main content
rule

py-fast-api — Cursor rule: what it does, how to install

A Cursor rule for Python FastAPI backends. It guides route structure, Pydantic validation, async I/O, dependency injection, and error handling.

Install into Cursor · Manually: put the files in place All methods and platforms ↓
.cursor/rules/py-fast-api.mdc
Open on GitHub

What py-fast-api does

This rule guides Cursor while building Python services with FastAPI. It favors plain functions, type annotations on every signature, and Pydantic models for request validation instead of untyped dictionaries. Route code is organized around exported routers, sub-routes, utilities, static content, and schemas. The guidance also covers dependency injection and explicit response types.

Error paths are handled early with guard clauses and returns, while middleware is used for logging, monitoring, and unexpected failures. For application startup and shutdown, it points to lifespan context managers rather than frequent use of @app.on_event. The dependency section names FastAPI, Pydantic v2, async database libraries such as asyncpg or aiomysql, and SQLAlchemy 2.0 when ORM features are used.

The rule targets **/*, yet alwaysApply: false means Cursor does not attach it to every request automatically. Blocking database or external API calls also conflict with its async, non-blocking guidance.

What it helps with

  • design FastAPI route structure
  • validate requests with Pydantic models
  • separate sync code from async I/O
  • handle failures with guards and middleware
  • organize database access for async execution

Example prompts for the agent

  • Create a FastAPI user route with Pydantic request and response models.
  • Refactor this handler so invalid states return early and nested conditions are removed.
  • Split this API into routers, utilities, and schemas, using async calls for database work.

How to install py-fast-api

Manually: put the files in place

.cursor/rules/py-fast-api.mdc

Frontmatter: description, globs, alwaysApply

Step by step, with commands for each platform: Cursor rules: .mdc files, four modes and what replaced .cursorrules

Questions about py-fast-api

How do I install py-fast-api in Cursor?

Place the rule file at .cursor/rules/py-fast-api.mdc.

What does py-fast-api do?

It sets coding guidance for Python FastAPI projects, including typing, Pydantic schemas, route organization, dependency injection, middleware, and error handling.

Which dependencies does py-fast-api cover?

It names FastAPI, Pydantic v2, and async database libraries such as asyncpg or aiomysql. SQLAlchemy 2.0 is included when ORM features are used.

Source text

py-fast-api.mdc · CC0-1.0
---
description: "Cursor rules for Python FastAPI backend development and best practices."
globs: **/*
alwaysApply: false
---
You are an expert in Python, FastAPI, and scalable API development.

Key Principles

- Write concise, technical responses with accurate Python examples.
- Use functional, declarative programming; avoid classes where possible.
- Prefer iteration and modularization over code duplication.
- Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).
- Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).
- Favor named exports for routes and utility functions.
- Use the Receive an Object, Return an Object (RORO) pattern.

Python/FastAPI

- Use def for pure functions and async def for asynchronous operations.
- Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
- File structure: exported router, sub-routes, utilities, static content, types (models, schemas).
- Avoid unnecessary curly braces in conditional statements.
- For single-line statements in conditionals, omit curly braces.
- Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).

Error Handling and Validation

- Prioritize error handling and edge cases:
  - Handle errors and edge cases at the beginning of functions.
  - Use early returns for error conditions to avoid deeply nested if statements.
  - Place the happy path last in the function for improved readability.
  - Avoid unnecessary else statements; use the if-return pattern instead.
  - Use guard clauses to handle preconditions and invalid states early.
  - Implement proper error logging and user-friendly error messages.
  - Use custom error types or error factories for consistent error handling.

Dependencies

- FastAPI
- Pydantic v2
- Async database libraries like asyncpg or aiomysql
- SQLAlchemy 2.0 (if using ORM features)

FastAPI-Specific Guidelines

- Use functional components (plain functions) and Pydantic models for input validation and response schemas.
- Use declarative route definitions with clear return type annotations.
- Use def for synchronous operations and async def for asynchronous ones.
- Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events.
- Use middleware for logging, error monitoring, and performance optimization.
- Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading.
- Use HTTPException for expected errors and model them as specific HTTP responses.
- Use middleware for handling unexpected errors, logging, and error monitoring.
- Use Pydantic's BaseModel for consistent input/output validation and response schemas.

Performance Optimization

- Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests.
- Implement caching for static and frequently accessed data using tools like Redis or in-memory stores.
- Optimize data serialization and deserialization with Pydantic.
- Use lazy loading techniques for large datasets and substantial API responses.

Key Conventions

1. Rely on FastAPI’s dependency injection system for managing state and shared resources.
2. Prioritize API performance metrics (response time, latency, throughput).
3. Limit blocking operations in routes:
   - Favor asynchronous and non-blocking flows.
   - Use dedicated async functions for database and external API operations.
   - Structure routes and dependencies clearly to optimize readability and maintainability.

Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.

© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules

Similar IDE rules

All IDE rules for Backend and APIs →

From the same set210

python-312-fastapi-best-practices-cursorrules-prom Guides Cursor to build FastAPI backends using Python 3.12, Poetry, and SQLAlchemy. It configures standard libraries for auth, emails, rate limiting, and migrations. ★ 41,024repo stars python--typescript-guide-cursorrules-prompt-file This rule guides Cursor on Python and TypeScript work with Django, React, Tailwind, and InertiaJS. It fits projects that need readable code and explicit file references. ★ 41,024repo stars pyspark-etl-best-practices-cursorrules-prompt-file A Cursor rule that sets PySpark code style: F.col(), explicit joins, select over withColumn, and Iceberg-aware ETL structure. ★ 41,024repo stars pyqt6-eeg-processing-cursorrules-prompt-file Configures Cursor for building PyQt6 desktop apps focused on EEG signal processing and data visualization. Helps separate heavy analysis from the interface. ★ 41,024repo stars project-epic-template-cursorrules-prompt-file This rule turns Cursor into a product manager: the agent writes epics and user stories with acceptance criteria and success metrics. ★ 41,024repo stars pr-template-cursorrules-prompt-file Sets up the agent to generate structured Pull Request templates for GitHub, GitLab, and Azure DevOps. Helpful for standardizing team code reviews. ★ 41,024repo stars pr-review-cursorrules-prompt-file A Cursor rule for focused pull request reviews across security, performance, tests, and architecture, with file-line references and severity labels. ★ 41,024repo stars postgresql A Cursor rule that pins down how the agent writes PostgreSQL: parameterized queries, TIMESTAMPTZ, indexes on foreign keys. Useful once the agent starts touching your SQL. ★ 41,024repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor