Back to Rules
Python

FastAPI Python Best Practices: Cursor Rules for Scalable API Development

Claude Directory November 29, 2025
0 copies 4 downloads

Unlock expert FastAPI Python guidelines rewritten for optimal code quality, async performance, error handling, and modular structure to build high-performance APIs efficiently.

Rule Content
1. **Embrace Functional and Declarative Styles**: Opt for pure functions over classes, promoting iteration and modular code to eliminate duplication and enhance reusability.

2. **Choose Descriptive Naming Conventions**: Use clear variable names with helper verbs like 'is_valid' or 'has_access', and name files/directories in snake_case (e.g., 'auth_handlers.py').

3. **Implement Named Exports**: Export specific routes and helper functions by name to improve modularity and ease of imports in FastAPI projects.

4. **Adopt RORO Pattern**: Design functions to accept a single input object and return a single output object for cleaner, predictable data flow.

5. **Distinguish Sync and Async Functions**: Define synchronous pure logic with 'def' and I/O operations with 'async def' to leverage FastAPI's async capabilities.

6. **Mandate Type Hints and Pydantic Models**: Annotate all parameters and returns; validate inputs/outputs using Pydantic v2 models instead of plain dicts for robustness.

7. **Organize Project Structure Logically**: Group code into folders for main routers, sub-routes, utilities, static assets, and type definitions (schemas/models).

8. **Simplify Conditional Logic**: Skip braces for single-line if statements and use one-liners like 'if condition: action()' for brevity.

9. **Prioritize Early Error Handling**: Employ guard clauses at function starts for edge cases, early returns to flatten nesting, and reserve the main success logic for the end.

10. **Eliminate Unneeded Else Blocks**: Rely on if-return patterns to streamline control flow and boost readability without redundant else clauses.

11. **Harness Dependency Injection**: Manage shared resources and state via FastAPI's built-in DI system for testable, decoupled code.

12. **Favor Lifespan Managers**: Handle app startup/shutdown with context managers instead of deprecated on_event hooks for better resource control.

13. **Deploy Middleware Strategically**: Add middleware for logging, error tracking, and perf tweaks like CORS or rate limiting.

14. **Optimize for Async Performance**: Go fully async for DB queries and external calls; integrate Redis caching, Pydantic tuning, and lazy data loading.

15. **Standardize Error Responses**: Raise HTTPException for anticipated issues and use middleware for unhandled errors with logging and user-safe messages.

Comments

More Rules

View all
AI/ML

GLM-4.7 Optimized Config & System Prompt Designer

Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.

C
Community
AI/ML

GLM-4.7 Open-Source Coding Expert: Optimized System Prompt

Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.

C
Community
AI/ML

GLM-4.7 Optimized Coding Agent

This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.

C
Community
DevOps

Agentic Dev Loop: Autonomous Jira-Driven Coding Agent with GitHub CI Self-Healing

Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.

C
Claude Directory
AI/ML

Türk Hukuku Uzmanı AI Agent: Güvenilir Yasal Danışman System Prompt

Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.

C
Community
Database

PostgreSQL Best Practices: Expert Subagent Guide

Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.

C
Claude Directory