FastAPI 教程
FastAPI 是一个现代、高性能的 Python Web 框架,专为构建 API 而设计。它基于 Python 类型提示,提供自动化的数据验证、序列化和 API 文档生成。
什么是 FastAPI?
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Python Web 框架。它的核心理念是:
- 快速:性能极高,与 NodeJS 和 Go 相当
- 快速编码:开发效率提升约 200%-300%
- 更少 Bug:减少约 40% 的人为错误
- 直观:优秀的编辑器支持,自动补全随处可见
- 简单:易于学习和使用
- 健壮:自动生成交互式文档
核心特性
基于开放标准
- OpenAPI:自动生成 OpenAPI 规范(原 Swagger)
- JSON Schema:自动生成数据模型文档
- 多语言客户端生成:基于 OpenAPI 规范自动生成客户端代码
自动文档
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
运行后访问:
http://127.0.0.1:8000/docs- Swagger UI 交互式文档http://127.0.0.1:8000/redoc- ReDoc 替代文档
类型提示驱动
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
"""商品模型"""
name: str
price: float
is_offer: bool = False
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
只需一次类型声明,即可获得:
- 编辑器自动补全
- 数据验证
- 自动类型转换
- 自动文档生成
高性能
FastAPI 基于 Starlette 和 Pydantic,性能极其出色:
2024-2025 新特性
FastAPI 持续进化,以下是近期版本的重要更新:
Server-Sent Events (SSE) 支持
版本 0.135.0+ 内置 SSE 支持,简化实时推送:
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse
app = FastAPI()
@app.get("/stream", response_class=EventSourceResponse)
async def stream_data():
for i in range(10):
yield {"count": i} # 自动 JSON 编码
流式响应增强
版本 0.134.0+ 支持直接 yield 返回流式数据:
@app.get("/json-lines")
async def stream_json():
for item in items:
yield item # 自动转为 JSON Lines 格式
JSON 性能优化
版本 0.130.0+ 使用 Pydantic 在 Rust 中序列化 JSON,性能提升 2 倍以上。无需额外配置,自动生效。
严格 Content-Type 检查
版本 0.132.0+ 默认启用 JSON 请求的 Content-Type 验证,提升安全性:
# 可选禁用(兼容旧客户端)
@app.post("/items", strict_content_type=False)
async def create_item(item: Item):
return item
OpenAPI Webhooks
完整支持 OpenAPI 3.1 的 Webhooks 定义:
from fastapi import FastAPI
app = FastAPI()
@app.webhook("post")
def new_item_webhook(item: Item):
"""新商品创建时触发的 Webhook"""
pass
与其他框架对比
| 特性 | FastAPI | Flask | Django | Express (Node.js) |
|---|---|---|---|---|
| 性能 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 类型提示 | 原生支持 | 需手动 | 部分支持 | TypeScript |
| 自动文档 | 内置 | 需扩展 | 需扩展 | 需扩展 |
| 异步支持 | 原生 | 需扩展 | 部分支持 | 原生 |
| 学习曲线 | 低 | 低 | 中 | 低 |
| 数据验证 | 内置 Pydantic | 需手动 | Form/Model | 需库 |
FastAPI 技术栈
适用场景
适合使用 FastAPI 的场景
- REST API 开发:构建高性能的 RESTful API
- 微服务架构:轻量级、高性能的服务
- 后端服务:移动应用、Web 前端的后端
- 机器学习服务:部署 ML 模型为 API
- 实时应用:WebSocket 支持
- 数据处理 API:数据验证和转换
可能不太适合的场景
- 传统 CMS 网站:考虑 Django
- 简单静态网站:考虑 Flask 或纯静态
- 需要完整 Admin 后台:考虑 Django Admin
教程目录
入门基础
核心功能
进阶特性
安全认证
- 安全认证 - OAuth2、JWT、API Key 认证
数据库集成
- 数据库集成 - SQLModel、CRUD 操作、关系映射
测试与部署
参考资料
- 速查表 - FastAPI 常用语法速查
快速开始
# main.py
from fastapi import FastAPI
app = FastAPI(
title="我的 API",
description="一个示例 API",
version="1.0.0"
)
@app.get("/")
async def root():
"""根路径"""
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
"""获取商品信息"""
return {"item_id": item_id, "q": q}
运行:
# 安装
pip install "fastapi[standard]"
# 开发模式运行
fastapi dev main.py
# 生产模式运行
fastapi run main.py
学习建议
- 先掌握 Python 类型提示:FastAPI 高度依赖类型提示
- 理解 Pydantic:数据验证的核心
- 从简单开始:先构建基本的 CRUD API
- 使用自动文档:充分利用 Swagger UI 测试 API
- 异步优先:理解
async/await的使用场景