.cursorrules Python FastAPI Backend

Python FastAPI スケーラブルAPI

PythonとFastAPIによるスケーラブルAPI構築のエキスパートルール。非同期優先、Pydantic検証、モジュラーアーキテクチャ。

.cursorrules · 64 lines
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 databases or SQLAlchemy 2.0 with async support
- SQLAlchemy 2.0 (if using ORM features)

FastAPI-Specific Guidelines
- Use functional components (plain functions) instead of class-based views.
- Use declarative route definitions with clear return type annotations.
- Use Pydantic models for request and response schemas.
- Implement dependency injection using FastAPI's Depends.
- Use lifespan context managers for startup and shutdown events.
- Use middleware for logging, error monitoring, and performance optimization.
- Optimize for async operations using asyncio and appropriate async libraries.
- Use BackgroundTasks for non-blocking operations like sending emails or processing data.
- Implement caching strategies using tools like Redis or in-memory caches.
- Use lazy loading techniques for large datasets and optimize database queries.

Performance Optimization
- Minimize blocking I/O operations; use async alternatives.
- Implement caching for frequently accessed data using Redis or in-memory stores.
- Optimize database queries; use indexing and query optimization techniques.
- Use connection pooling for database and external service connections.
- Implement proper pagination for large data sets.
- Use lazy loading for heavy resources and implement background processing for intensive tasks.

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 async operations for I/O-bound tasks.
   - Use dedicated async functions for database and external API calls.
   - Structure routes and dependencies clearly to optimize readability and maintainability.

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

こちらもおすすめ

Backend カテゴリの他のルール

もっとルールを探す

CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 157 ルールをチェック。