第一章:FastAPI 简介¶
什么是 FastAPI?¶
FastAPI 是一个现代、高性能的 Python Web 框架,用于构建 API。它基于标准的 Python 类型提示,自动生成 API 文档,支持异步编程。
核心特性¶
1. 高性能¶
FastAPI 的性能可与 NodeJS 和 Go 媲美,这得益于:
- Starlette:高性能异步框架
- Pydantic:快速的数据验证
- Uvicorn:ASGI 服务器
性能对比:
| 框架 | 请求/秒 |
|---|---|
| FastAPI | ~21,000 |
| Flask | ~2,000 |
| Django | ~1,500 |
2. 快速开发¶
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
name: str
age: int
@app.post("/users/")
def create_user(user: User):
return {"message": f"Created user {user.name}"}
自动获得: - ✅ 请求体验证 - ✅ 自动 API 文档 - ✅ 编辑器支持
3. 自动文档¶
FastAPI 自动生成交互式 API 文档:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
4. 类型提示¶
from typing import Optional
def get_user(user_id: int, name: Optional[str] = None):
# 编辑器自动补全
# 类型检查
# 自动文档生成
pass
为什么选择 FastAPI?¶
优点¶
| 优点 | 说明 |
|---|---|
| 高性能 | 异步支持,性能优异 |
| 开发快 | 自动文档,减少代码 |
| 少 Bug | 类型检查,提前发现错误 |
| 易学习 | 设计直观,文档完善 |
| 生产就绪 | 被Netflix、Uber等使用 |
适用场景¶
- ✅ RESTful API 开发
- ✅ 微服务架构
- ✅ 异步任务处理
- ✅ 实时应用(WebSocket、SSE)
- ✅ 机器学习服务部署
FastAPI vs 其他框架¶
vs Flask¶
| 特性 | FastAPI | Flask |
|---|---|---|
| 异步支持 | ✅ 原生 | ❌ 需扩展 |
| 类型验证 | ✅ 自动 | ❌ 手动 |
| API 文档 | ✅ 自动 | ❌ 需扩展 |
| 性能 | 高 | 中 |
vs Django¶
| 特性 | FastAPI | Django |
|---|---|---|
| 学习曲线 | 低 | 高 |
| 灵活性 | 高 | 中 |
| 全栈 | ❌ | ✅ |
| 性能 | 高 | 中 |
安装 FastAPI¶
# 安装 FastAPI 和 Uvicorn
pip install fastapi uvicorn[standard]
# 或使用 pipenv
pipenv install fastapi uvicorn[standard]
第一个 FastAPI 应用¶
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
运行:
访问: - API: http://localhost:8000 - 文档: http://localhost:8000/docs
项目结构推荐¶
project/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI 应用入口
│ ├── config.py # 配置文件
│ ├── models/ # 数据模型
│ │ ├── __init__.py
│ │ └── user.py
│ ├── routers/ # 路由模块
│ │ ├── __init__.py
│ │ └── users.py
│ ├── services/ # 业务逻辑
│ │ └── __init__.py
│ └── utils/ # 工具函数
│ └── __init__.py
├── tests/ # 测试文件
├── requirements.txt
└── README.md
小结¶
本章学习了:
- ✅ FastAPI 的核心特性
- ✅ 为什么选择 FastAPI
- ✅ 如何安装和运行
- ✅ 第一个 FastAPI 应用
下一章¶
第二章:快速开始 - 深入学习 FastAPI 的核心功能。