Skip to main content
rule

python-fastapi-best-practices-cursorrules-prompt-f — Cursor rule

A Cursor rule that sets the agent's coding style for Python and FastAPI: functional code, Pydantic v2, async operations.

Install into Cursor · Manually: put the files in place All methods and platforms ↓
.cursor/rules/python-fastapi-best-practices-cursorrules-prompt-f.mdc
Open on GitHub

What python-fastapi-best-practices-cursorrules-prompt-f does

The rule plugs into Cursor and tells the agent how to write code in a FastAPI project. Inside is a set of conventions: functional and declarative style, classes only where they are unavoidable, modularization instead of duplicated code. Variable names carry auxiliary verbs like is_active or has_permission, directories and files stay lowercase with underscores, for example routers/user_routes.py.

Data handling and errors get their own section. Input validation and response schemas use Pydantic models rather than raw dictionaries. Expected errors go through HTTPException with specific HTTP responses, while middleware catches the unexpected ones and handles logging. Blocking I/O is kept to a minimum: every database call and external API request is asynchronous.

The rule expects FastAPI, Pydantic v2 and an async database library such as asyncpg or aiomysql, plus SQLAlchemy 2.0 if you use ORM features. On Pydantic v1 the schema advice is worth rechecking by hand. For startup and shutdown events it points you to lifespan context managers instead of @app.on_event.

What it helps with

  • set one coding style for the agent across a FastAPI project
  • move input validation from raw dicts to Pydantic models
  • keep blocking database calls out of request handlers
  • replace startup and shutdown event handlers with lifespan
  • lay out routers and utilities in a predictable file structure

Example prompts for the agent

  • Write a user router with async def, type hints and Pydantic v2 schemas
  • Rewrite these handlers to use lifespan instead of @app.on_event
  • Scan this module for blocking I/O and suggest async alternatives

How to install python-fastapi-best-practices-cursorrules-prompt-f

Manually: put the files in place

.cursor/rules/python-fastapi-best-practices-cursorrules-prompt-f.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 python-fastapi-best-practices-cursorrules-prompt-f

How do I install python-fastapi-best-practices-cursorrules-prompt-f in Cursor?

Create .cursor/rules/python-fastapi-best-practices-cursorrules-prompt-f.mdc in your project root and paste the rule text into it.

What does this rule do?

It sets the Cursor agent's style for Python and FastAPI work: functional components, Pydantic models for validation, async I/O and errors raised through HTTPException.

Which library versions does the rule assume?

It targets FastAPI, Pydantic v2 and async libraries such as asyncpg or aiomysql, with SQLAlchemy 2.0 when ORM features are in play.

Source text

python-fastapi-best-practices-cursorrules-prompt-f.mdc · CC0-1.0
---
description: "Cursor rules for Python FastAPI development with best practices."
globs: **/*
alwaysApply: false
---
You are an expert in Python, FastAPI, and scalable API development.

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. 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()).

Prioritize error handling and edge cases:

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

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. 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. 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 set68

rails-cursorrules-prompt-file A Cursor rule file that tells the agent how to write Rails 8 code: generators, bin/dev, the Solid stack, Minitest and Hotwire. ★ 41,011repo stars qwik-basic-cursorrules-prompt-file A Cursor rule that sets Qwik conventions for the agent: lazy functions with the $ suffix, signals, tasks, and a TypeScript plus Vite project layout. ★ 41,011repo stars python A Cursor rule that sets project layout, code style and stack choices for Python work with Flask and SQLite. Useful when the agent edits files in your repo. ★ 41,011repo stars python-github-setup-cursorrules-prompt-file Tells Cursor how to write and review Python code: style, tests, GitHub Pull Requests and GitHub Actions CI. Useful when the team has no shared rulebook. ★ 41,011repo stars python-cursorrules-prompt-file-best-practices A Cursor rule that makes the assistant write Python with type annotations, PEP 257 docstrings and pytest tests. ★ 41,011repo 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,011repo 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,011repo stars playwright-defect-tracking-cursorrules-prompt-file A Cursor rule that makes the agent write Playwright tests tied to manual case IDs, with screenshots and logs as defect evidence. ★ 41,011repo 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