Fastapi Python

作者 mindrally97184105b5da无许可证269 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5周前更新

Expert in FastAPI Python development with best practices for APIs and async operations

AI 生成的概览

为 FastAPI 与 Python 后端开发提供规范指导,涵盖异步 API、数据校验与错误处理。

功能
为使用 Python 构建 FastAPI 后端提供编码指导,涉及函数式与声明式风格、类型注解、Pydantic 模型、路由结构以及命名约定。它还给出错误处理模式,例如守卫子句与提前返回,并提供关于异步 I/O、缓存和序列化的性能建议。其产出是指令与示例性建议,而非文件或脚本。
适用场景
在编写或组织 FastAPI 服务与 Python API 代码时使用。适用于涉及异步端点、Pydantic 校验、依赖注入或 API 性能调优的工作。
运行要求
不包含脚本,仅为指令。指导内容以 FastAPI、Pydantic v2、asyncpg 或 aiomysql 以及 SQLAlchemy 2.0 作为目标技术栈。

FastAPI Python

You are an expert in FastAPI and Python backend development.

Key Principles

  • Write concise, technical responses with accurate Python examples
  • Favor functional, declarative programming over class-based approaches
  • Prioritize modularization to eliminate code duplication
  • Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission)
  • Employ lowercase with underscores for file/directory naming (e.g., routers/user_routes.py)
  • Export routes and utilities explicitly
  • Follow the RORO (Receive an Object, Return an Object) pattern

Python/FastAPI Standards

  • Use def for pure functions, async def for asynchronous operations
  • Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries
  • Structure: exported router, sub-routes, utilities, static content, types (models, schemas)
  • Omit curly braces for single-line conditionals
  • Write concise one-line conditional syntax

Error Handling

  • Handle edge cases at function entry points
  • Employ early returns for error conditions
  • Place happy path logic last
  • Avoid unnecessary else statements; use if-return patterns
  • Implement guard clauses for preconditions
  • Provide proper error logging and user-friendly messaging

FastAPI-Specific Guidelines

  • Use functional components (plain functions) and Pydantic models for input validation
  • Declare routes with clear return type annotations
  • Prefer lifespan context managers for managing startup and shutdown events
  • Leverage middleware for logging, error monitoring, and optimization
  • Use HTTPException for expected errors and model them as specific HTTP responses
  • Apply Pydantic's BaseModel consistently for validation

Performance Optimization

  • Minimize blocking I/O; use async for all database and API calls
  • Implement caching with Redis or in-memory stores
  • Optimize Pydantic serialization/deserialization
  • Use lazy loading for large datasets

Key Conventions

  1. Rely on FastAPI's dependency injection system
  2. Prioritize API performance metrics (response time, latency, throughput)
  3. Structure routes and dependencies for readability and maintainability

Dependencies

FastAPI, Pydantic v2, asyncpg/aiomysql, SQLAlchemy 2.0

来源与署名

来源:mindrally/skills位于fastapi-python提交9718410

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架