用 Python 构建高性能 API 的现代框架
FastAPI 是一个现代、快速的 Python Web 框架,专为构建 API 而设计。它以高性能、自动文档和类型安全著称。本课程将从零开始,带你理解 FastAPI 的核心概念。
FastAPI 是一个用于构建 API 的 Python Web 框架,由 Sebastián Ramírez 在 2018 年创建。它的名字就是 "Fast" + "API" —— 快速的 API。
FastAPI 的核心特点:
FastAPI 就是 Python 世界的 "Express.js" —— 但比 Express 更快、更安全、文档更好。写几个函数就能得到一个完整的 API 服务。
FastAPI 基于 Starlette(异步 Web 框架)和 Pydantic(数据验证库),支持 Python 的 async/await 异步编程,性能非常出色。
| 框架 | 性能(请求/秒) | 语言 |
|---|---|---|
| FastAPI | 非常高 | Python |
| Flask | 中等 | Python |
| Django | 中等 | Python |
| Express | 高 | Node.js |
| Go (net/http) | 非常高 | Go |
FastAPI 会根据你的代码自动生成交互式 API 文档。启动服务后,访问 /docs 就能看到 Swagger UI 文档,访问 /redoc 就能看到 ReDoc 文档。不需要写一行文档代码!
GET 请求用于获取数据,是最常见的 HTTP 方法。
from fastapi import FastAPI
app = FastAPI()
# 定义一个 GET 接口
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
# 带路径参数的 GET 接口
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
# 带查询参数的 GET 接口
@app.get("/search")
def search(q: str, limit: int = 10):
return {"query": q, "limit": limit}
访问方式:
GET / → 返回 {"message": "Hello, World!"}GET /items/42 → 返回 {"item_id": 42}GET /search?q=python&limit=5 → 返回 {"query": "python", "limit": 5}POST 请求用于创建数据,通常携带请求体(Body)。
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_name": item.name, "item_price": item.price}
/items/{item_id}/search?q=pythonPydantic 是 FastAPI 的 "数据管家",它负责:
from pydantic import BaseModel, Field
from typing import Optional
class UserCreate(BaseModel):
username: str = Field(..., min_length=3, max_length=50, description="用户名")
email: str = Field(..., description="邮箱地址")
age: int = Field(..., gt=0, lt=150, description="年龄")
nickname: Optional[str] = Field(None, description="昵称(可选)")
# 使用
@app.post("/users")
def create_user(user: UserCreate):
return {"username": user.username, "email": user.email}
如果客户端发送了 {"age": "25"}(字符串),Pydantic 会自动转换为整数 25。如果发送了 {"age": -1},Pydantic 会自动返回 422 错误 —— 因为设置了 gt=0(大于 0)。
Pydantic 常用的验证器:
| 验证器 | 含义 | 示例 |
|---|---|---|
min_length | 最小长度 | Field(min_length=3) |
max_length | 最大长度 | Field(max_length=50) |
gt / ge | 大于 / 大于等于 | Field(gt=0) |
lt / le | 小于 / 小于等于 | Field(lt=150) |
pattern | 正则匹配 | Field(pattern="^\\d+$") |
依赖注入(Dependency Injection)是 FastAPI 的一个强大特性。简单来说,它让你可以把一些 "公共逻辑" 抽取出来,在多个接口中复用。
from fastapi import FastAPI, Depends, Header, HTTPException
app = FastAPI()
# 定义一个依赖:验证 API Key
def verify_api_key(x_api_key: str = Header(...)):
if x_api_key != "my-secret-key":
raise HTTPException(status_code=401, detail="Invalid API Key")
return x_api_key
# 在接口中使用依赖
@app.get("/protected")
def protected_route(api_key: str = Depends(verify_api_key)):
return {"message": "你通过了验证!"}
@app.get("/also-protected")
def another_protected(api_key: str = Depends(verify_api_key)):
return {"message": "这里也需要验证"}
常见的依赖注入场景:
这是 FastAPI 最酷的特性之一 —— 你写的代码自动变成交互式 API 文档。
启动 FastAPI 应用后,你会得到两个文档页面:
| 地址 | 文档类型 | 特点 |
|---|---|---|
/docs | Swagger UI | 交互式,可以直接在页面上测试 API |
/redoc | ReDoc | 阅读式,更美观,适合给前端/产品看 |
/openapi.json | OpenAPI JSON | 机器可读的标准格式 |
# 启动服务后访问:
# http://localhost:8000/docs → Swagger UI 交互式文档
# http://localhost:8000/redoc → ReDoc 美观文档
# http://localhost:8000/openapi.json → OpenAPI JSON
# 文档中的信息来自:
# 1. 你的路径装饰器(@app.get, @app.post 等)
# 2. 你的 Pydantic 模型(自动生成参数说明)
# 3. 你的函数文档字符串(docstring)
@app.get("/items/{item_id}", summary="获取商品详情", description="根据商品 ID 获取商品的详细信息")
def read_item(item_id: int):
"""这是一个获取商品详情的接口"""
return {"item_id": item_id}
把上面学的知识串起来,这是一个完整的 FastAPI 应用:
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel, Field
from typing import List, Optional
app = FastAPI(title="我的第一个 API", version="1.0.0")
# Pydantic 模型
class ItemCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
price: float = Field(..., gt=0)
description: Optional[str] = None
class ItemResponse(BaseModel):
id: int
name: str
price: float
description: Optional[str]
# 模拟数据库
items_db = []
next_id = 1
# GET - 获取所有商品
@app.get("/items", response_model=List[ItemResponse], summary="获取商品列表")
def list_items(skip: int = 0, limit: int = 10):
return items_db[skip : skip + limit]
# GET - 获取单个商品
@app.get("/items/{item_id}", response_model=ItemResponse, summary="获取商品详情")
def get_item(item_id: int):
for item in items_db:
if item["id"] == item_id:
return item
raise HTTPException(status_code=404, detail="商品不存在")
# POST - 创建商品
@app.post("/items", response_model=ItemResponse, summary="创建商品", status_code=201)
def create_item(item: ItemCreate):
global next_id
new_item = {"id": next_id, **item.model_dump()}
items_db.append(new_item)
next_id += 1
return new_item
/docs 提供 Swagger UI 交互式文档,在 /redoc 提供 ReDoc 文档。Depends() 在多个接口中复用,同时方便测试时替换(mock)。理解了 FastAPI 的基础后,可以继续学习: