FastAPI 简介 #
什么是 API? #
在了解 FastAPI 之前,我们需要先理解 API(Application Programming Interface,应用程序编程接口)的概念。API 是软件系统之间通信的桥梁。
text
┌─────────────────────────────────────────────────────────────┐
│ API 的本质 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 类比: │
│ │
│ ┌─────────┐ 请求/响应 ┌─────────┐ │
│ │ 客户端 │ <──────────────> │ 服务端 │ │
│ └─────────┘ └─────────┘ │
│ │
│ 就像: │
│ - 餐厅菜单:了解可以点什么菜 │
│ - 银行窗口:办理各种业务 │
│ - 遥控器:控制电视的各种功能 │
│ │
└─────────────────────────────────────────────────────────────┘
RESTful API #
text
┌─────────────────────────────────────────────────────────────┐
│ RESTful API 设计 │
├─────────────────────────────────────────────────────────────┤
│ │
│ HTTP 方法对应 CRUD 操作: │
│ │
│ GET /users → 获取用户列表(Read) │
│ GET /users/1 → 获取单个用户(Read) │
│ POST /users → 创建新用户(Create) │
│ PUT /users/1 → 更新用户(Update) │
│ DELETE /users/1 → 删除用户(Delete) │
│ │
└─────────────────────────────────────────────────────────────┘
什么是 FastAPI? #
FastAPI 是一个现代、高性能的 Python Web 框架,专门用于构建 API。它由 Sebastián Ramírez(tiangolo)于 2018 年创建,基于 Starlette(Web 框架)和 Pydantic(数据验证)构建。
核心定位 #
text
┌─────────────────────────────────────────────────────────────┐
│ FastAPI │
├─────────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 高性能 │ │ 自动文档 │ │ 类型提示 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 异步支持 │ │ 数据验证 │ │ 依赖注入 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────┘
FastAPI 的历史 #
发展历程 #
text
2018年 ─── FastAPI 诞生
│
│ Sebastián Ramírez 创建
│ 基于 Starlette + Pydantic
│ 解决 Flask/Django 的痛点
│
2019年 ─── 快速增长
│
│ 社区活跃
│ 大量企业采用
│
2020年 ─── 生态成熟
│
│ 丰富的扩展
│ 完善的文档
│
2021年 ─── 企业级应用
│
│ Netflix、Uber 等采用
│ 生产环境验证
│
至今 ─── 行业标准
│
│ Python API 首选框架
│ 持续更新迭代
里程碑版本 #
| 版本 | 时间 | 重要特性 |
|---|---|---|
| 0.1.0 | 2018 | 初始发布 |
| 0.40.0 | 2019 | WebSocket 支持 |
| 0.50.0 | 2020 | 依赖注入增强 |
| 0.60.0 | 2020 | 后台任务 |
| 0.70.0 | 2021 | 性能优化 |
| 0.80.0 | 2022 | Pydantic v2 支持 |
| 0.100.0 | 2023 | 稳定版本 |
为什么选择 FastAPI? #
传统框架的局限 #
在使用 FastAPI 之前,Python Web 开发面临以下问题:
python
# Flask:需要手动处理很多事情
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
# 手动验证数据
if not data.get('name'):
return jsonify({'error': 'name required'}), 400
# 手动生成文档
# ...
return jsonify({'id': 1, 'name': data['name']})
FastAPI 的解决方案 #
python
# FastAPI:自动验证、自动文档
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
email: str
@app.post('/users')
def create_user(user: User):
return {'id': 1, 'name': user.name, 'email': user.email}
# 自动验证、自动生成 OpenAPI 文档!
FastAPI 的核心特点 #
1. 高性能 #
text
┌─────────────────────────────────────────────────────────────┐
│ 性能对比 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 框架 请求/秒 相对性能 │
│ │
│ FastAPI ~22,000 ████████████████████ │
│ NodeJS ~21,000 ███████████████████ │
│ Go ~25,000 ██████████████████████ │
│ Flask ~2,000 ██ │
│ Django ~1,500 █ │
│ │
│ FastAPI 是 Python 中最快的框架之一! │
│ │
└─────────────────────────────────────────────────────────────┘
2. 自动 API 文档 #
python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post('/items/')
def create_item(item: Item):
return item
自动生成:
- Swagger UI:
/docs - ReDoc:
/redoc - OpenAPI JSON:
/openapi.json
3. 类型提示与数据验证 #
python
from typing import Optional
from pydantic import BaseModel, Field, EmailStr
class User(BaseModel):
id: int
name: str = Field(..., min_length=2, max_length=50)
email: EmailStr
age: Optional[int] = Field(None, ge=0, le=150)
# 自动验证:
# - name 长度 2-50
# - email 格式正确
# - age 在 0-150 之间
4. 异步支持 #
python
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
async def read_root():
# 异步操作,不阻塞
await some_async_operation()
return {'message': 'Hello'}
@app.get('/sync')
def read_sync():
# 同步操作也支持
return {'message': 'Hello'}
5. 依赖注入 #
python
from fastapi import Depends, FastAPI
app = FastAPI()
def get_db():
db = Database()
try:
yield db
finally:
db.close()
@app.get('/users')
def get_users(db = Depends(get_db)):
return db.query(User).all()
FastAPI 与其他框架对比 #
FastAPI vs Flask #
| 特性 | FastAPI | Flask |
|---|---|---|
| 性能 | 极高 | 中等 |
| 异步 | 原生支持 | 需要扩展 |
| 类型验证 | 自动 | 手动 |
| API文档 | 自动生成 | 需要扩展 |
| 学习曲线 | 中等 | 平缓 |
| WebSocket | 原生支持 | 需要扩展 |
FastAPI vs Django #
| 特性 | FastAPI | Django |
|---|---|---|
| 定位 | API框架 | 全栈框架 |
| 性能 | 极高 | 中等 |
| 灵活性 | 高 | 中等 |
| ORM | 可选 | 内置 |
| Admin | 无 | 内置 |
| 体积 | 轻量 | 较重 |
FastAPI vs Express (Node.js) #
| 特性 | FastAPI | Express |
|---|---|---|
| 语言 | Python | JavaScript |
| 类型 | 可选 | 无 |
| 文档 | 自动 | 需要工具 |
| 异步 | async/await | 回调/Promise |
| 性能 | 相近 | 相近 |
FastAPI 的应用场景 #
1. RESTful API #
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
email: str
users_db = {}
@app.get('/users/{user_id}')
def get_user(user_id: int):
if user_id not in users_db:
raise HTTPException(status_code=404, detail='User not found')
return users_db[user_id]
@app.post('/users')
def create_user(user: User):
users_db[user.id] = user
return user
2. 微服务架构 #
text
┌─────────────────────────────────────────────────────────────┐
│ 微服务架构 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ 用户服务 │ │ 订单服务 │ │ 支付服务 │ │
│ │FastAPI │ │FastAPI │ │FastAPI │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
│ │ │ │ │
│ └─────────────┼─────────────┘ │
│ │ │
│ ┌───────┴───────┐ │
│ │ API Gateway │ │
│ └───────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
3. 实时应用 #
python
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f'Message: {data}')
4. 机器学习 API #
python
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
app = FastAPI()
model = joblib.load('model.pkl')
class Input(BaseModel):
features: list[float]
@app.post('/predict')
def predict(input: Input):
prediction = model.predict([input.features])
return {'prediction': prediction.tolist()}
FastAPI 的技术栈 #
text
┌─────────────────────────────────────────────────────────────┐
│ FastAPI 技术栈 │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ FastAPI │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ ┌────────────────┼────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
│ │ Starlette │ │ Pydantic │ │ Uvicorn │ │
│ │ Web框架 │ │ 数据验证 │ │ ASGI服务器 │ │
│ └───────────┘ └───────────┘ └───────────┘ │
│ │
│ Starlette: 提供路由、中间件、WebSocket 等核心功能 │
│ Pydantic: 提供数据验证、序列化、设置管理 │
│ Uvicorn: 提供高性能 ASGI 服务器 │
│ │
└─────────────────────────────────────────────────────────────┘
FastAPI 的核心概念 #
路径操作 #
python
@app.get('/') # GET 请求
@app.post('/') # POST 请求
@app.put('/') # PUT 请求
@app.delete('/') # DELETE 请求
@app.patch('/') # PATCH 请求
路径参数 #
python
@app.get('/items/{item_id}')
def read_item(item_id: int):
return {'item_id': item_id}
查询参数 #
python
@app.get('/items')
def read_items(skip: int = 0, limit: int = 10):
return {'skip': skip, 'limit': limit}
请求体 #
python
class Item(BaseModel):
name: str
price: float
@app.post('/items')
def create_item(item: Item):
return item
FastAPI 的优势与局限 #
优势 #
text
✅ 高性能
- 基于 Starlette 和 Uvicorn
- 与 NodeJS 和 Go 相当
- Python 中最快的框架之一
✅ 开发效率
- 类型提示自动补全
- 自动生成 API 文档
- 自动数据验证
✅ 现代化
- 原生异步支持
- WebSocket 支持
- OpenAPI 标准
✅ 易于测试
- TestClient 简单
- 依赖注入便于 mock
局限性 #
text
⚠️ 相对年轻
- 2018 年发布
- 生态不如 Django 成熟
⚠️ 学习曲线
- 需要理解类型提示
- 需要理解异步编程
⚠️ 功能范围
- 专注于 API
- 没有 Admin、模板等
学习路径 #
text
入门阶段
├── FastAPI 简介(本文)
├── 安装与配置
├── 第一个应用
└── 路径操作
进阶阶段
├── 请求与响应
├── 数据验证
├── 依赖注入
└── 安全认证
高级阶段
├── 数据库集成
├── 异步编程
├── 测试
└── 部署
下一步 #
现在你已经了解了 FastAPI 的基本概念,接下来学习 安装与配置,开始你的 FastAPI 开发之旅!
最后更新:2026-03-29