当 Python 开发者厌倦了 Flask 的"随意"和 Django 的"笨重"时,FastAPI 出现了。它以"快"为名,迅速成为 Python Web 开发的新宠。
FastAPI 是什么?#
FastAPI 是 Sebastian Ramirez 于 2018 年创建的现代 Python Web 框架。它的核心特点是:高性能、异步支持、自动文档、现代 Python。
类比理解#
| 对比项 | Django | Flask | FastAPI |
|---|---|---|---|
| 风格 | 全家桶 | 微型 | 现代微框架 |
| 异步 | 需要额外配置 | 需要额外配置 | 原生支持 |
| 文档 | Admin 后台 | 需要额外配置 | 自动生成 |
| 性能 | 较低 | 中等 | 非常高 |
| 就像 | 豪华轿车 | 自行车 | 电动车 |
FastAPI 的性能可以与 Node.js 和 Go 相媲美,是 Python 生态最快的框架之一。
核心特性#
1. 异步支持:async/await 原生#
FastAPI 原生支持 Python 的 async/await 语法:
from fastapi import FastAPI
import asyncio
app = FastAPI()
# 异步路径操作
@app.get("/async-data")
async def get_async_data():
# 使用 await 进行异步操作
data = await fetch_data_from_api()
return data
# 同步路径操作(也可以)
@app.get("/sync-data")
def get_sync_data():
data = fetch_data_sync()
return data
async def fetch_data_from_api():
await asyncio.sleep(1) # 模拟异步 IO
return {"message": "异步获取的数据"}
def fetch_data_sync():
time.sleep(1) # 模拟同步 IO
return {"message": "同步获取的数据"}2. 类型提示:现代 Python#
FastAPI 完全基于 Python 类型提示:
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional, List
app = FastAPI()
# 定义数据模型
class User(BaseModel):
name: str
email: str
age: Optional[int] = None
tags: List[str] = []
# 类型提示的路径参数
@app.get("/users/{user_id}")
async def get_user(user_id: int) -> User:
return User(
name="张三",
email="zhangsan@example.com",
age=25,
tags=["developer", "python"]
)
# 请求体
@app.post("/users")
async def create_user(user: User) -> User:
# 自动验证数据类型
return user3. 自动生成 API 文档#
FastAPI 自动生成交互式 API 文档:
- Swagger UI:
/docs - ReDoc:
/redoc
from fastapi import FastAPI
app = FastAPI(
title="我的 API",
description="这是一个示例 API",
version="1.0.0"
)
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
"""
读取项目
- **item_id**: 项目 ID
- **q**: 可选的查询参数
"""
if q:
return {"item_id": item_id, "q": q}
return {"item_id": item_id}访问 http://localhost:8000/docs 即可看到自动生成的交互式文档。
4. 数据验证:Pydantic#
FastAPI 使用 Pydantic 进行数据验证:
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, Field, validator
app = FastAPI()
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=50)
email: EmailStr # 自动验证邮箱格式
password: str = Field(..., min_length=8)
age: int = Field(ge=0, le=150) # 年龄范围验证
@validator('password')
def password_strength(cls, v):
if not any(c.isupper() for c in v):
raise ValueError('密码必须包含大写字母')
if not any(c.isdigit() for c in v):
raise ValueError('密码必须包含数字')
return v
@app.post("/users/")
async def create_user(user: UserCreate):
return {"username": user.username, "email": user.email}5. 依赖注入:强大的 DI 系统#
FastAPI 提供了强大的依赖注入系统:
from fastapi import FastAPI, Depends, HTTPException
from typing import Annotated
app = FastAPI()
# 模拟数据库
fake_db = {"alice": {"email": "alice@example.com"}}
# 定义依赖
async def get_current_user(token: str = Depends(lambda: "current_user")):
if token != "valid_token":
raise HTTPException(status_code=401, detail="未授权")
return {"username": "alice", "email": "alice@example.com"}
# 使用依赖
@app.get("/profile")
async def get_profile(user: dict = Depends(get_current_user)):
return user
# 类作为依赖
class QueryParams:
def __init__(self, q: str = "default", skip: int = 0, limit: int = 10):
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items")
async def read_items(params: QueryParams = Depends(QueryParams)):
return {"q": params.q, "skip": params.skip, "limit": params.limit}6. 中间件支持#
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# CORS 中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def add_header(request, call_next):
response = await call_next(request)
response.headers["X-Custom-Header"] = "FastAPI"
return response为什么 FastAPI 如此流行?#
1. 性能极高#
FastAPI 基于 Starlette(Web 框架)和 Pydantic(数据验证),性能接近 Node.js 和 Go:
| 框架 | 每秒请求数 |
|---|---|
| FastAPI | 35,000+ |
| Flask | 6,000+ |
| Django | 3,000+ |
| Node.js | 30,000+ |
| Go | 50,000+ |
2. 开发体验好#
- 类型提示:代码提示更准确
- 自动文档:省去写文档的时间
- 错误提示:清晰的错误信息
3. 现代 Python#
完全基于 Python 3.7+ 的现代特性:
- 类型提示
- async/await
- dataclasses
4. 适合微服务#
FastAPI 非常适合构建微服务:
- 轻量
- 快速启动
- 易于部署
- 原生支持异步
适用场景#
| 场景 | 适合程度 | 说明 |
|---|---|---|
| REST API | ⭐⭐⭐⭐⭐ | 核心场景 |
| 微服务 | ⭐⭐⭐⭐⭐ | 轻量快速 |
| ML/AI 服务 | ⭐⭐⭐⭐⭐ | Python 原生 |
| 实时应用 | ⭐⭐⭐⭐ | WebSocket 支持 |
| 简单 Web 应用 | ⭐⭐⭐ | 可以,但 Flask 更简单 |
| 大型全栈应用 | ⭐⭐⭐ | 可以,Django 更适合 |
学习路线建议#
入门阶段(1 周)#
- 掌握 Python 基础和类型提示
- 理解 FastAPI 基本用法
- 学会定义路径操作
- 掌握 Pydantic 模型
进阶阶段(1-2 周)#
- 深入依赖注入
- 掌握异步数据库操作
- 学会使用 SQLModel
- 理解中间件
高级阶段(持续学习)#
- 性能优化
- 部署(Docker、UVicorn)
- 测试
- 与其他服务集成
与其他 Python 框架对比#
| 特性 | FastAPI | Flask | Django |
|---|---|---|---|
| 性能 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐ |
| 易用性 | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
| 功能完整 | ⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| 文档自动生成 | ⭐⭐⭐⭐⭐ | ⭐ | ⭐⭐⭐ |
| 异步支持 | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐ |
| 适合场景 | API、微服务 | 小型应用 | 大型全栈 |
简单来说:
- FastAPI:API 开发首选,性能高,现代
- Flask:轻量灵活,适合小型项目
- Django:全栈框架,适合大型项目
常用扩展#
# 数据库
pip install sqlalchemy
pip install databases
pip install sqlmodel
# 认证
pip install python-jose[cryptography]
pip install passlib[bcrypt]
# 验证
pip install email-validator
# 异步
pip install uvicorn[standard]
pip install httpx总结#
FastAPI 为 Python 开发者提供了一个现代、高效的 API 开发选择:
- 高性能—— 接近 Node.js 和 Go
- 异步原生—— 充分利用 Python async/await
- 自动文档—— 省去编写 API 文档的时间
- 类型提示—— 更好的开发体验和代码提示
- Pydantic 验证—— 强大的数据验证能力
如果你需要构建 Python API,特别是微服务或 ML/AI 相关的服务,FastAPI 是最佳选择。
下期预告:FastAPI 用的是 Python,而 NestJS 用的是 TypeScript—— 它把 Angular 的架构思想带到了后端开发。下一篇文章我们来详细介绍这个"Node.js 版的 Spring Boot"。
