FastAPI 心智模型:类型驱动的 API 框架
核心理念
FastAPI 的设计哲学:用 Python 类型提示描述 API 契约,框架自动完成验证、序列化和文档生成。
传统 Flask 方式
python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/items', methods=['POST'])
def create_item():
data = request.get_json()
# 手动验证
if 'name' not in data or not isinstance(data['name'], str):
return jsonify({"error": "name is required"}), 400
if 'price' not in data or not isinstance(data['price'], (int, float)):
return jsonify({"error": "price must be a number"}), 400
# 业务逻辑
return jsonify({"name": data['name'], "price": data['price']})FastAPI 方式
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):
# 类型错误自动返回 422,无需手动验证
return {"name": item.name, "price": item.price}三大支柱
1. Pydantic 数据验证
python
from pydantic import BaseModel, Field, EmailStr
class User(BaseModel):
email: EmailStr
age: int = Field(..., ge=18, le=120)
name: str = Field(..., min_length=1, max_length=50)
# 自动验证:
# - email 格式
# - age 在 18-120 之间
# - name 长度 1-502. Starlette ASGI 性能
python
@app.get("/sync")
def sync_endpoint():
return {"message": "同步"}
@app.get("/async")
async def async_endpoint():
await some_io_operation()
return {"message": "异步"}3. 自动 OpenAPI 文档
启动应用后访问:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- OpenAPI JSON: http://localhost:8000/openapi.json
类型提示的威力
python
from typing import Optional, List
@app.get("/users")
async def get_users(
skip: int = 0, # 必填,整数
limit: int = 100, # 可选,默认 100
search: Optional[str] = None # 可选字符串
) -> List[dict]:
# 类型错误自动拦截,无需 if/else
return users[skip:skip + limit]发送错误类型:
bash
GET /users?skip=abc自动返回 422:
json
{
"detail": [
{
"loc": ["query", "skip"],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}与其他框架对比
| 特性 | FastAPI | Flask | Django REST |
|---|---|---|---|
| 类型提示 | 原生 | 需插件 | 需序列化器 |
| 自动验证 | ✅ | ❌ | ✅ |
| 自动文档 | ✅ | 需插件 | 需配置 |
| 异步支持 | ✅ | 部分 | ❌ |
| 性能 | 高 | 中 | 中 |
学习路径
- 掌握 Python 类型提示(typing 模块)
- 理解 Pydantic 模型
- 学习路径操作(@app.get/post/put/delete)
- 掌握依赖注入系统
- 理解异步编程(async/await)
下一步:进入可运行实验创建第一个 FastAPI 应用。
返回第一章概览
返回第一章概览