FastAPI 是近年来 Python 生态中增长最快的 Web 框架之一,因其高性能、强类型、自动化文档、优秀的异步支持,已成为构建 API 服务、AI 推理接口、数据服务的主流选择。
本文将从纯后端技术视角系统介绍 FastAPI 的核心能力、设计理念与工程化实践,适合作为技术论坛文章或内部技术文档。
1. FastAPI 是什么?
FastAPI 是一个基于 Python 类型注解(Type Hints) 构建的现代 Web 框架,底层基于:
- Starlette:高性能 ASGI Web 框架
- Pydantic:数据校验与序列化库
- Uvicorn:高性能 ASGI 服务器(基于 uvloop + httptools)
其核心目标是:
用最少的代码,构建类型安全、性能优秀、文档齐全的 API 服务。
2. FastAPI 的核心特性
FastAPI 的设计并非"语法糖",而是围绕工程效率展开:
- 基于 Python 类型注解的 请求校验与自动解析
- 自动生成 OpenAPI / Swagger 文档
- 原生支持
async / await - 高并发性能(ASGI 架构)
- 与 AI / 数据科学生态天然兼容
- 明确区分「路由层 / 数据模型 / 业务逻辑」
3. 快速开始:最小可运行 API
3.1 安装依赖
python
pip install fastapi uvicorn
- FastAPI:Web 框架
- Uvicorn:ASGI 服务器(类似 Gunicorn + async 支持)
3.2 创建入口文件 main.py
python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello FastAPI"}
3.3 启动服务
python
uvicorn main:app --reload
参数说明:
main:模块名app:FastAPI 实例--reload:开发模式,自动重启
3.4 自动 API 文档
FastAPI 启动后自动生成文档:
-
Swagger UI
bashhttp://localhost:8000/docs -
ReDoc
bashhttp://localhost:8000/redoc
文档完全基于 OpenAPI 3.0 标准,无需手写。
4. 路由系统与路径参数
4.1 基础路由
python
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
特点:
user_id: int自动触发类型校验- 非法参数将返回
422 Unprocessable Entity - 参数信息同步出现在文档中
4.2 请求方法声明
FastAPI 通过装饰器明确声明 HTTP 方法:
python
@app.post("/users")
@app.put("/users/{id}")
@app.delete("/users/{id}")
每个路由即是一个明确的 HTTP 语义接口。
5. 请求体与数据模型(Pydantic)
FastAPI 使用 Pydantic 模型定义请求与响应结构。
5.1 定义数据模型
python
from pydantic import BaseModel
class UserCreate(BaseModel):
name: str
age: int
Pydantic 的能力包括:
- 类型校验
- 数据转换
- 默认值
- 字段描述(用于文档)
5.2 在接口中使用
python
@app.post("/users")
def create_user(user: UserCreate):
return user
FastAPI 将自动完成:
- JSON → Python 对象
- 字段校验
- 错误信息标准化返回
- 文档同步更新
6. 参数来源说明(Query / Path / Body)
FastAPI 明确区分参数来源:
6.1 Query 参数
python
@app.get("/search")
def search(keyword: str, limit: int = 10):
return {"keyword": keyword, "limit": limit}
6.2 Path 参数
python
@app.get("/items/{item_id}")
def get_item(item_id: int):
return {"item_id": item_id}
6.3 Body 参数(Pydantic)
python
@app.post("/login")
def login(data: LoginModel):
return data
参数来源清晰,避免隐式行为。
7. 响应模型与状态码
7.1 默认行为
python
return {"message": "ok"}
FastAPI 自动序列化为 JSON。
7.2 自定义状态码
python
from fastapi import status
@app.post("/users", status_code=status.HTTP_201_CREATED)
def create_user(user: UserCreate):
return user
7.3 响应模型(推荐)
python
@app.post("/users", response_model=UserCreate)
def create_user(user: UserCreate):
return user
优势:
- 限制返回字段
- 提高接口一致性
- 防止敏感字段泄露
8. 中间件机制
FastAPI 中间件基于 Starlette,适用于:
- 日志
- 认证
- 跨域
- 请求追踪
示例:CORS 中间件
python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
9. 数据库集成(示例)
FastAPI 不绑定 ORM,可自由选择:
- SQLAlchemy(主流)
- Tortoise ORM
- SQLModel(FastAPI 作者推荐)
- Prisma Client Python
示例:SQLAlchemy Engine
python
from sqlalchemy import create_engine
engine = create_engine(
"sqlite:///./test.db",
echo=True,
future=True
)
通常配合:
- Session 管理
- Dependency Injection
- Repository 层封装
10. 文件上传与二进制处理
python
from fastapi import File, UploadFile
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
content = await file.read()
return {
"filename": file.filename,
"size": len(content)
}
FastAPI 内置支持:
- Multipart
- 流式读取
- 大文件处理
11. 项目工程结构(推荐)
bash
app/
├── main.py # 应用入口
├── routers/ # 路由模块
├── schemas/ # Pydantic 模型
├── models/ # ORM 模型
├── services/ # 业务逻辑
├── core/ # 配置 / 安全 / 中间件
└── database/ # 数据库连接
符合 高内聚、低耦合、可测试 的后端工程原则。
12. FastAPI 的典型应用场景
- AI / LLM 推理接口
- 后台管理系统 API
- 数据处理服务
- 自动化工具 API 化
- 微服务 / 内部服务
- Serverless API
13. 总结
FastAPI 并不是"Flask 的替代品",而是:
面向现代工程实践的 Python API 框架
它将类型系统、接口文档、异步性能、工程规范整合为一个整体,极大降低了构建高质量 API 服务的成本。