Python FastAPI Development Rules

5/28/2025

这组规则提供了FastAPI开发的最佳实践。包括使用Pydantic模型处理请求和响应模式、实现依赖注入、使用异步/等待进行非阻塞操作、遵循特定的文件夹结构、使用类型提示、进行输入验证、处理后台任务、跨域资源共享(CORS)和安全问题、遵循PEP 8风格指南以及进行全面的单元和集成测试。


    # Python FastAPI .cursorrules

# FastAPI best practices

fastapi_best_practices = [
    "Use Pydantic models for request and response schemas",
    "Implement dependency injection for shared resources",
    "Utilize async/await for non-blocking operations",
    "Use path operations decorators (@app.get, @app.post, etc.)",
    "Implement proper error handling with HTTPException",
    "Use FastAPI's built-in OpenAPI and JSON Schema support",
]

# Folder structure

folder_structure = """
app/
  main.py
  models/
  schemas/
  routers/
  dependencies/
  services/
  tests/
"""

# Additional instructions

additional_instructions = """
1. Use type hints for all function parameters and return values
2. Implement proper input validation using Pydantic
3. Use FastAPI's background tasks for long-running operations
4. Implement proper CORS handling
5. Use FastAPI's security utilities for authentication
6. Follow PEP 8 style guide for Python code
7. Implement comprehensive unit and integration tests
"""