fastapi
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFastAPI
FastAPI
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.8+ based on standard Python type hints. It is one of the fastest Python frameworks available.
FastAPI是一个现代、快速(高性能)的Web框架,用于基于标准Python类型提示构建Python 3.8+版本的API。它是目前速度最快的Python框架之一。
When to Use
使用场景
- APIs: The default choice for modern Python APIs.
- Machine Learning: Native integration with Pydantic makes JSON <-> Model interaction seamless.
- Performance: Built on Starlette and Pydantic v2, it rivals Node.js and Go in benchmarks.
- API开发:现代Python API的默认选择。
- 机器学习:与Pydantic原生集成,实现JSON与模型之间的无缝交互。
- 性能需求:基于Starlette和Pydantic v2构建,在基准测试中性能可与Node.js和Go媲美。
Quick Start
快速开始
python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return {"name": item.name, "price": item.price}python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
async def create_item(item: Item):
return {"name": item.name, "price": item.price}Core Concepts
核心概念
Pydantic Models
Pydantic模型
Define data shape using Python classes. Validation and JSON serialization happen automatically.
使用Python类定义数据结构。自动完成验证和JSON序列化。
Dependency Injection
依赖注入
FastAPI has a powerful DI system.
.
async def read_users(db: Session = Depends(get_db)):FastAPI拥有强大的依赖注入系统。示例:。
async def read_users(db: Session = Depends(get_db)):OpenAPI (Swagger)
OpenAPI(Swagger)
Automatically generates interactive API documentation at .
/docs会在路径自动生成交互式API文档。
/docsBest Practices (2025)
2025年最佳实践
Do:
- Use Pydantic v2: Ensure you are on v2 for the massive Rust-based performance boost.
- Use : Use the new
lifespancontext manager for startup/shutdown events instead of deprecatedlifespan.on_event - Type Everything: The more you type, the better the auto-generated docs and validation.
Don't:
- Don't block the loop: Run CPU bound code (image processing, heavy math) in endpoints (threadpool), not
def(event loop), or use background tasks.async def
建议:
- 使用Pydantic v2:确保使用v2版本,以获得基于Rust的大幅性能提升。
- 使用:使用新的
lifespan上下文管理器处理启动/关闭事件,替代已弃用的lifespan。on_event - 全面添加类型提示:类型提示越完善,自动生成的文档和验证效果越好。
避免:
- 不要阻塞事件循环:CPU密集型代码(如图像处理、复杂运算)应放在端点(线程池)中运行,而非
def(事件循环),或使用后台任务。async def