在现代 Web 开发领域,用户对接口响应速度、系统并发能力的要求日益严苛,性能已经成为衡量 Web 框架优劣的核心指标之一。同时,开发者也越来越关注开发效率——减少重复的文档编写、数据验证代码,让精力聚焦在业务逻辑上。
FastAPI 作为近几年崛起的高性能 Python Web 框架,完美契合了这些趋势:它原生支持异步编程,能充分利用现代服务器的多核资源;内置基于 Pydantic 的数据验证和自动生成的交互式 API 文档;兼容 OpenAPI 规范,兼具高性能与开发便捷性,成为众多开发者从 Flask 等传统框架迁移的首选。
场景 | Flask (同步) | FastAPI (异步) | 性能提升幅度 |
|---|---|---|---|
简单接口 QPS (单进程) | ~800 | ~3000 | 约 275% |
带IO操作接口 (如数据库查询) | ~100 | ~2000 | 约 1900% |
并发连接数支持 | ~1000 | ~10000+ | 约 900% |
注:测试环境为 Python 3.10,4核8G服务器,测试工具为 locust,数据为行业通用基准测试结果。
首先安装依赖:
pip install fastapi uvicorn# main.py
from fastapi import FastAPI
# 初始化 FastAPI 应用实例
app = FastAPI(
title="我的第一个 FastAPI 应用", # 文档标题
description="FastAPI 入门示例", # 文档描述
version="1.0.0" # 版本号
)
# 定义 GET 请求路由,路径为根路径 "/"
@app.get("/")
def read_root():
"""根路径接口,返回简单的问候信息"""
return {"Hello": "World"}
# 带路径参数的 GET 接口
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
"""根据 item_id 查询物品,q 为可选查询参数"""
return {"item_id": item_id, "q": q}
# 启动命令(终端执行):uvicorn main:app --reloaduvicorn main:app --reload(--reload 开启热重载,开发环境使用){"Hello":"World"}


FastAPI 支持异步函数(async def),在处理需要等待外部资源(如数据库、API 调用)的任务时,线程不会阻塞,而是去处理其他请求,直到等待的资源返回结果。
# main.py
import asyncio
from fastapi import FastAPI
app = FastAPI()
# 同步接口(对比用)
@app.get("/sync")
def sync_operation():
# 模拟同步IO等待(会阻塞整个线程)
import time
time.sleep(1) # 等待1秒
return {"status": "completed", "type": "sync"}
# 异步接口
@app.get("/async")
async def async_operation():
# 模拟异步IO等待(不会阻塞线程)
await asyncio.sleep(1) # 异步等待1秒
return {"status": "completed", "type": "async"}测试效果:用压测工具同时发起 100 个请求,同步接口耗时约 100 秒(串行等待),异步接口仅耗时约 1 秒(并行等待)。
FastAPI 结合 Pydantic 模型实现自动数据验证和类型转换,无需手动编写校验逻辑。
from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, Field
app = FastAPI()
# 定义数据模型(Pydantic BaseModel)
class User(BaseModel):
username: str = Field(min_length=3, max_length=50, description="用户名,3-50个字符")
email: EmailStr # 自动验证邮箱格式
age: int = Field(ge=18, le=120, description="年龄,18-120岁")
is_active: bool = True # 默认值
# 接收并验证 POST 请求体
@app.post("/users/")
async def create_user(user: User):
# user 已自动验证并转换为对象,可直接访问属性
return {
"message": f"用户 {user.username} 创建成功",
"user_data": user.dict() # 序列化为字典返回
}验证效果:如果传入 age=17 或 email="invalid-email",FastAPI 会自动返回 422 错误,并清晰提示验证失败的原因,无需手动处理。
FastAPI 的依赖注入系统可以轻松实现:权限校验、数据库连接、参数解析、资源复用等功能,让代码更模块化。
from fastapi import FastAPI, Depends
import sqlite3
app = FastAPI()
# 定义依赖函数:获取数据库连接
def get_db():
conn = sqlite3.connect("mydb.db")
try:
yield conn # 提供连接给接口使用
finally:
conn.close() # 接口执行完后关闭连接
# 接口使用依赖
@app.get("/db-items/")
async def get_db_items(db: sqlite3.Connection = Depends(get_db)):
cursor = db.cursor()
cursor.execute("SELECT * FROM items")
items = cursor.fetchall()
return {"items": items}FastAPI 内置对 OAuth2、JWT 等认证方式的支持,结合第三方库可快速实现安全校验。
python-jose 和 passlib)pip install python-jose[cryptography] passlib[bcrypt]from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import datetime, timedelta
# 配置
SECRET_KEY = "your-secret-key-keep-it-safe" # 生产环境需用环境变量
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
app = FastAPI()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# 模拟用户数据库
fake_users_db = {
"johndoe": {
"username": "johndoe",
"hashed_password": pwd_context.hash("secret"),
"email": "johndoe@example.com",
}
}
# 生成 Token
def create_access_token(data: dict):
to_encode = data.copy()
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
# 验证 Token 获取当前用户
async def get_current_user(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="无法验证凭据",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = fake_users_db.get(username)
if user is None:
raise credentials_exception
return user
# 获取 Token 接口
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = fake_users_db.get(form_data.username)
if not user or not pwd_context.verify(form_data.password, user["hashed_password"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="用户名或密码错误",
)
access_token = create_access_token(data={"sub": user["username"]})
return {"access_token": access_token, "token_type": "bearer"}
# 受保护的接口
@app.get("/users/me")
async def read_users_me(current_user: dict = Depends(get_current_user)):
return current_user构建一个简单的待办事项(Todo)API,包含:数据库集成(SQLAlchemy)、CRUD 操作、错误处理、数据验证。
# todo_app.py
from fastapi import FastAPI, HTTPException, Depends, status
from pydantic import BaseModel, Field
from sqlalchemy import create_engine, Column, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
# 1. 数据库配置
SQLALCHEMY_DATABASE_URL = "sqlite:///./todos.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# 2. 数据库模型
class TodoDB(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, nullable=True)
completed = Column(Boolean, default=False)
# 创建数据库表
Base.metadata.create_all(bind=engine)
# 3. Pydantic 模型(数据验证/序列化)
class TodoCreate(BaseModel):
title: str = Field(min_length=1, max_length=100)
description: str | None = Field(None, max_length=500)
class TodoUpdate(BaseModel):
title: str | None = Field(None, min_length=1, max_length=100)
description: str | None = Field(None, max_length=500)
completed: bool | None = None
class Todo(TodoCreate):
id: int
completed: bool
class Config:
orm_mode = True # 支持从 ORM 对象转换为 Pydantic 模型
# 4. FastAPI 应用初始化
app = FastAPI(title="Todo API", version="1.0")
# 5. 依赖:获取数据库会话
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# 6. CRUD 接口
# 创建 Todo
@app.post("/todos/", response_model=Todo, status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
db_todo = TodoDB(**todo.dict())
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
# 获取所有 Todo
@app.get("/todos/", response_model=list[Todo])
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
todos = db.query(TodoDB).offset(skip).limit(limit).all()
return todos
# 获取单个 Todo
@app.get("/todos/{todo_id}", response_model=Todo)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
todo = db.query(TodoDB).filter(TodoDB.id == todo_id).first()
if todo is None:
raise HTTPException(status_code=404, detail="Todo 不存在")
return todo
# 更新 Todo
@app.put("/todos/{todo_id}", response_model=Todo)
def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
db_todo = db.query(TodoDB).filter(TodoDB.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo 不存在")
# 只更新传入的字段
update_data = todo.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_todo, key, value)
db.commit()
db.refresh(db_todo)
return db_todo
# 删除 Todo
@app.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
db_todo = db.query(TodoDB).filter(TodoDB.id == todo_id).first()
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo 不存在")
db.delete(db_todo)
db.commit()
return Nonepip install fastapi uvicorn sqlalchemyuvicorn todo_app:app --reload开发环境:uvicorn 带热重载
生产环境:使用 gunicorn + uvicorn 工作进程,示例命令:
gunicorn todo_app:app -w 4 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000

FastAPI 并非简单的“新框架”,而是 Python Web 开发的一次升级:它将异步性能、类型提示、自动文档、数据验证等现代开发理念融为一体,既满足了高性能服务的需求,又大幅降低了开发者的心智负担。
未来,随着 Python 异步生态的持续完善,以及 FastAPI 社区的不断壮大(目前 GitHub 星数已超 60k),它将在微服务、API 网关、实时数据接口、AI 服务接口等领域占据更重要的地位。
动手实践是掌握 FastAPI 的最佳方式——从简单接口开始,逐步集成数据库、认证、部署,你会发现它能轻松应对从小型项目到大型分布式系统的各类需求。