FastAPI:路由、校验、文档
本合集目录
本章目录
单册说明:本文件是卷 5 的第 5 章,可独立阅读。前置:5.3(虚拟环境)、5.4(手写服务的痛点)。本章用 FastAPI 重写五个端点,并把"校验"和"文档"交给类型系统。
| 项 | 内容 |
|---|---|
| 所属卷 | 卷 5 · 后端与 API(第 5 / 8 章) |
| 前置章节 | 5.4 手搓一个 HTTP 服务 |
| 本章产出 | /api/notes 的 5 个端点 + 自动文档 /docs + 一份 Pydantic 模型 |
| 对应代码 | backend/app/main.py、backend/app/models.py、backend/app/store.py |
| 配图 | 无(后续统一制图) |
| 读完的判定 | 能在 /docs 里点完五个端点;能解释 201 与 204 为什么都不带"多余的话" |
5.5.1 一句话结论:你写签名,框架写校验和文档
上一章手写校验是这样的(摘自 do_POST 方法体):
if not (data.get("title") or "").strip():
return self.fail(422, "invalid", "title 不能为空")
问题不在长短,在于它只防住了你想得到的情况。title 传了 500 个字符呢?传了数字 123 呢?source_url 传了个对象呢?每漏一个,脏数据就进了一次存储。
FastAPI 的做法是把这件事前移:
class NoteCreate(BaseModel):
title: str = Field(min_length=1, max_length=120)
这一行同时做了三件事:声明类型、生成校验、写进文档。 请求进来先过模型,不合格的连你的函数都进不去。
真实收益长这样(实测):
POST /api/notes {"title": "", "content": "x"}
[422]
{"detail":[{"type":"string_too_short","loc":["body","title"],
"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}}]}
注意最后那个 input 和 ctx:它告诉你哪个字段、错在哪、你传了什么。 手写校验要写到这个程度,得写不少代码。
5.5.2 原理与方法
三行启动,但要知道每行在说什么
python -m uvicorn app.main:app --reload --port 8000
| 片段 | 含义 | 换掉会怎样 |
|---|---|---|
python -m uvicorn |
用当前虚拟环境里的 uvicorn 启动 | 裸写 uvicorn 可能用到别的环境里的版本 |
app.main:app |
从 app/main.py 里取名为 app 的对象 |
名字写错 → Error loading ASGI app |
--reload |
改文件自动重启 | 只在开发用;生产上它会让进程管理变复杂 |
--port 8000 |
监听端口 | 8000 被占用时换一个,别去动别人的进程 |
app 这个对象就是"整个应用"。所有路由、中间件、错误处理都挂在它身上;uvicorn 只负责"接 TCP 连接,把请求交给它"。
参数从哪来:三条规则,不用背
| 你把它写在哪 | FastAPI 认为是 | 例子 |
|---|---|---|
路径里出现了 {name} |
路径参数 | /api/notes/{note_id} |
函数签名里是简单类型(int str bool)且路径里没有 |
查询参数 | ?tag=js&limit=20 |
| 是 Pydantic 模型 | 请求体 | {"title": "..."} |
这三条足以覆盖本书所有接口。唯一的例外是"简单类型但你偏要它从 body 来",那要显式写 Body(...)——本书用不到。
类型即校验:Pydantic v2 的常用约束
from pydantic import BaseModel, Field, field_validator
class NoteCreate(BaseModel):
title: str = Field(min_length=1, max_length=120)
content: str = Field(min_length=1, max_length=5000)
source_url: str | None = Field(default=None, max_length=500)
| 写法 | 校验什么 | 失败时的 type |
|---|---|---|
str / int / bool |
类型(会尝试转换,"12" → 12) |
string_type / int_parsing |
str | None |
允许 null |
— |
Field(min_length=1) |
最短长度(按字符算) | string_too_short |
Field(max_length=5000) |
最长长度 | string_too_long |
Field(ge=1, le=100) |
数值区间 | greater_than_equal |
Field(pattern=r"^https?://") |
正则 | string_pattern_mismatch |
Field(default=None) |
可不传 | — |
@field_validator |
自定义规则 | value_error |
⚠️ v1 与 v2 的写法差异会让旧教程误导你:
| 你在网上看到的(v1) | 现在应该写(v2) |
|---|---|
class Config: orm_mode = True |
model_config = ConfigDict(from_attributes=True) |
note.dict() |
note.model_dump() |
note.json() |
note.model_dump_json() |
@validator("title") |
@field_validator("title") |
Field(..., regex="...") |
Field(..., pattern="...") |
v1 的写法在 v2 里要么报 PydanticUserError,要么给一条 DeprecationWarning 然后继续跑——继续跑更危险,因为你会以为没问题。看到 dict() 就换掉。
必填还是可选:只看有没有默认值
这是新手最容易看错的一处,因为两种写法长得很像:
| 写法 | 必填? | 为什么 |
|---|---|---|
title: str |
必填 | 没有默认值 |
title: str = Field(min_length=1) |
必填 | Field() 里没写 default,等价于没有默认值 |
source_url: str | None = None |
可选 | 有默认值 None |
source_url: str | None = Field(default=None) |
可选 | 显式写了 default |
漏传必填字段时,实测返回(注意 type 是 missing,而不是某个类型错误):
{"detail":[{"type":"missing","loc":["body","content"],"msg":"Field required","input":{"title":"空内容"}}]}
input 里会回显你发的那份 JSON——这也是为什么请求体里不要塞敏感信息,它可能出现在错误响应和日志里(5.6 讲过)。
⚠️ 另一个常被忽略的点:str | None 里 None 是类型,不是默认值。写成 title: str | None(没写 = None),它仍然是必填,只是允许传 null。这个区别在表单里表现为"字段明明写了可空,为什么还报 required"。
三个"响应"相关的参数
| 参数 | 作用 | 不写的后果 |
|---|---|---|
response_model=Note |
按模型裁剪输出,并写进文档 | 内部字段(将来的 user_id、password_hash)会一起发出去 |
status_code=201 |
声明成功状态码 | 新建也返回 200,前端无法区分"新建了"和"已存在" |
status_code=204 |
成功但无响应体 | 前端还要解析一个空体,容易 Unexpected end of JSON input |
response_model 是本书的安全底线:它保证"发出去的字段"是一个白名单。卷 6 加了 user_id 之后,这条线会救你一次——忘记裁剪就会把别人的 id 泄露出去。
/docs 与 /openapi.json:文档不是写出来的,是长出来的
启动后打开 http://127.0.0.1:8000/docs,你会看到一个可交互的页面。它读的是 /openapi.json,可以直接问它有几个端点:
curl -s http://127.0.0.1:8000/openapi.json | python -c "
import json, sys
d = json.load(sys.stdin)
print(list(d['paths']))
print(list(d['paths']['/api/notes']['post']['responses']))
"
实测输出:
['/api/notes', '/api/notes/{note_id}']
['201', '422']
两个路径、POST 声明了两种响应——这就是文档的全部来源。
怎么用:
| 你想确认 | 在 /docs 里怎么看 |
|---|---|
| 字段名对不对 | 展开端点 → Schema 里逐个字段看 |
| 必填还是可选 | 字段后有没有红色的 * |
| 成功返回什么 | Responses → 200 / 201 的 Example Value |
| 失败返回什么 | Responses → 422,这里会列出校验错误的形状 |
| 直接试一次 | Try it out → 填参数 → Execute,能看到完整 curl 与响应 |
⚠️ 一个必须知道的边界:/docs 在公网是公开的。 它不泄露数据,但会把你所有端点和字段名摊开给扫描器。卷 7 上线时要么关掉它,要么加一层保护;现在本地开发,敞开用。
Depends:把"每个端点都要做的事"抽出来
三个端点(查、改、删)都要先做同一件事:
note = store.get_note(note_id)
if note is None:
raise HTTPException(status_code=404, detail="摘录不存在")
复制三遍不只是啰嗦,而是将来会改漏:卷 6 要在这里加"这条记录属于当前用户吗",改两处漏一处就是越权漏洞。
Depends 的写法:
def get_note_or_404(note_id: int) -> dict:
note = store.get_note(note_id)
if note is None:
raise HTTPException(status_code=404, detail="摘录不存在")
return note
NoteDep = Annotated[dict, Depends(get_note_or_404)]
然后端点签名里写 note: NoteDep,函数体直接拿到那条记录。这套机制的价值在于:
| 好处 | 说明 |
|---|---|
| 只写一次 | 404 逻辑、将来的权限检查都只有一处 |
| 自动进文档 | 依赖里的路径参数会被合并进端点签名 |
| 可替换 | 测试时用 app.dependency_overrides 换成假数据,不用连真存储 |
| 可组合 | 一个依赖可以再依赖别的依赖(卷 6 的"当前用户"就是这样) |
现在它只是省了十行代码;卷 6 你会发现它是放鉴权的地方。
CORS 这一章先不开
前端在 localhost:3000、后端在 127.0.0.1:8000,端口不同就是跨源。你现在用 curl 和 /docs 测都没问题,因为它们不受同源策略约束(同源策略是浏览器执行的)。等 5.7 你在浏览器里真的 fetch 一次,就会看到那条经典报错,那时再配。提前开等于给自己一个"能跑但不知道为什么会跑"的假象。
存储:本章先把数据落到一个 JSON 文件
# app/store.py 的核心
DATA_FILE = Path(__file__).resolve().parent.parent / "data" / "notes.json"
def _read() -> list[dict]:
if not DATA_FILE.exists():
return []
with DATA_FILE.open(encoding="utf-8") as f:
return json.load(f)
def _write(notes: list[dict]) -> None:
tmp = DATA_FILE.with_suffix(".tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(notes, f, ensure_ascii=False, indent=2)
tmp.replace(DATA_FILE)
三个设计点,各有原因:
| 写法 | 为什么 |
|---|---|
Path(__file__).resolve().parent.parent |
定位到 backend/,不受"从哪个目录启动"影响(5.3 坑三) |
ensure_ascii=False |
文件里存中文而不是 \u95ed\u5305,方便你亲眼看数据 |
先写 .tmp 再 replace |
写到一半崩溃时,旧文件还在;直接覆盖会留下半个 JSON |
⚠️ 这是临时方案,必须在正文里说清它的极限:
| 问题 | 现在会怎样 | 卷 6 怎么解决 |
|---|---|---|
| 并发写 | 两个请求同时读到旧数据,后写的覆盖先写的(丢数据) | 数据库事务 + 行锁 |
| 查询 | 每次全量读进内存再过滤 | SQL 索引 |
| 关联 | 标签只能塞进一个字段 | tags / note_tags 表 |
| 多用户 | 没有 user_id,谁都能看全部 |
加列 + 鉴权 |
threading.Lock() 只能保证"同一进程内不交叉写",挡不住多进程(卷 7 用 systemd 起单进程,暂时够用)。别在这个方案上做长期投资,它的寿命就是本卷。
5.5.3 动手:三个文件,五个端点
目录结构(在 backend/ 下):
backend/
app/
__init__.py
main.py
models.py
store.py
data/
notes.json ← 内容写 []
requirements.txt
app/models.py:
from datetime import datetime, timezone
from pydantic import BaseModel, Field, field_validator
def now_iso() -> str:
"""统一的时间格式:UTC、秒级、以 Z 结尾,形如 2026-11-17T09:30:00Z。"""
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
class NoteCreate(BaseModel):
title: str = Field(min_length=1, max_length=120)
content: str = Field(min_length=1, max_length=5000)
source_url: str | None = Field(default=None, max_length=500)
class NoteUpdate(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=120)
content: str | None = Field(default=None, min_length=1, max_length=5000)
source_url: str | None = Field(default=None, max_length=500)
@field_validator("title", "content")
@classmethod
def not_null(cls, value: str | None) -> str:
if value is None:
raise ValueError("不想改就别传这个字段;传了就必须是字符串")
return value
class Note(BaseModel):
id: int
title: str
content: str
source_url: str | None
created_at: str
app/store.py:
import json
import threading
from pathlib import Path
from .models import NoteCreate, NoteUpdate, now_iso
DATA_FILE = Path(__file__).resolve().parent.parent / "data" / "notes.json"
_lock = threading.Lock()
def _read() -> list[dict]:
if not DATA_FILE.exists():
return []
with DATA_FILE.open(encoding="utf-8") as f:
return json.load(f)
def _write(notes: list[dict]) -> None:
DATA_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = DATA_FILE.with_suffix(".tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(notes, f, ensure_ascii=False, indent=2)
tmp.replace(DATA_FILE)
def list_notes() -> list[dict]:
with _lock:
return _read()
def get_note(note_id: int) -> dict | None:
with _lock:
return next((n for n in _read() if n["id"] == note_id), None)
def create_note(payload: NoteCreate) -> dict:
with _lock:
notes = _read()
note = {
"id": max((n["id"] for n in notes), default=0) + 1,
**payload.model_dump(),
"created_at": now_iso(),
}
notes.append(note)
_write(notes)
return note
def update_note(note_id: int, payload: NoteUpdate) -> dict | None:
changes = payload.model_dump(exclude_unset=True)
with _lock:
notes = _read()
for note in notes:
if note["id"] == note_id:
note.update(changes)
_write(notes)
return note
return None
def delete_note(note_id: int) -> bool:
with _lock:
notes = _read()
kept = [n for n in notes if n["id"] != note_id]
if len(kept) == len(notes):
return False
_write(kept)
return True
app/main.py:
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from . import store
from .models import Note, NoteCreate, NoteUpdate
app = FastAPI(title="读到 API", version="0.1.0")
def get_note_or_404(note_id: int) -> dict:
note = store.get_note(note_id)
if note is None:
raise HTTPException(status_code=404, detail="摘录不存在")
return note
NoteDep = Annotated[dict, Depends(get_note_or_404)]
@app.get("/api/notes", response_model=list[Note], tags=["notes"])
def list_notes() -> list[dict]:
return store.list_notes()
@app.post("/api/notes", response_model=Note, status_code=status.HTTP_201_CREATED, tags=["notes"])
def create_note(payload: NoteCreate) -> dict:
return store.create_note(payload)
@app.get("/api/notes/{note_id}", response_model=Note, tags=["notes"])
def get_note(note: NoteDep) -> dict:
return note
@app.patch("/api/notes/{note_id}", response_model=Note, tags=["notes"])
def update_note(note: NoteDep, payload: NoteUpdate) -> dict:
return store.update_note(note["id"], payload)
@app.delete("/api/notes/{note_id}", status_code=status.HTTP_204_NO_CONTENT, tags=["notes"])
def delete_note(note: NoteDep) -> None:
store.delete_note(note["id"])
启动并跑一遍:
python -m uvicorn app.main:app --reload
curl -s http://127.0.0.1:8000/api/notes
# []
curl -s -X POST http://127.0.0.1:8000/api/notes \
-H "Content-Type: application/json" \
-d '{"title":"闭包","content":"函数记住它的词法环境","source_url":"https://example.com/closure"}'
# {"id":1,"title":"闭包","content":"函数记住它的词法环境",
# "source_url":"https://example.com/closure","created_at":"2026-11-16T18:24:15Z"}
curl -s http://127.0.0.1:8000/api/notes/1
curl -s -X PATCH http://127.0.0.1:8000/api/notes/1 \
-H "Content-Type: application/json" -d '{"title":"闭包(改)"}'
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE http://127.0.0.1:8000/api/notes/1
# 204
用 -i 看响应头,你会看到 HTTP/1.1 201 Created 和 content-length 为 0 的 204。201 与 204 都是"成功",区别只在有没有东西要交还。
最后打开 /docs 走一遍:
| 步骤 | 你会看到 |
|---|---|
展开 POST /api/notes → Try it out |
一个按 Schema 生成的 JSON 模板 |
把 title 删掉 → Execute |
422,响应体里指出 title 缺失 |
填回去 → Execute |
201,响应体是新建的那条 |
点 Schemas 里的 Note |
三个模型各自的字段与类型 |
这一步的意义:你从此有了一个不依赖记忆的接口说明书,而且它不会过期——它就是代码本身。
5.5.4 三个坑
坑一:把 /api/notes/{note_id} 写在 /api/notes/search 前面
症状:以后加一个"搜索"端点,GET /api/notes/search 返回 422,报 int_parsing:
{"detail":[{"type":"int_parsing","loc":["path","note_id"],
"msg":"Input should be a valid integer, unable to parse string as an integer","input":"search"}]}
成因:路由是按注册顺序匹配的,先命中的赢。{note_id} 也能匹配上 search 这一段,于是框架把 "search" 当 id 去转整数。
修法:静态路径写在动态路径前面。这条规则在所有框架里都成立(Nginx 的 location 也讲究顺序)。判断口诀:越具体的越靠前。
坑二:路径参数类型不对,返回的是 422 而不是 404
症状:前端把 id 传成了 "abc",你以为是"记录不存在",结果拿到 422;前端的 if (res.status === 404) 分支永远不触发,页面卡在 loading。
成因:note_id: int 是入口校验。类型不对,请求连函数都没进,自然不会走到"查不到 → 404"那一步。422 的语义是"你的请求形状不对",404 是"形状对了,但没这个资源"。
修法:两端各做一件事。① 前端只发数字 id,从 URL 拿到后先校验;② 前端把 422 也当成"请求有问题"来显示,不要只处理 404 和 500。别想着"把 422 改成 404"——那会让真正的参数错误失去线索。
坑三:PATCH 分不清"没传"和"传了 null"
症状:前端只想改标题,发了 {"title":"新标题"},结果 content 被清空了;或者反过来,发了 {"title":null},整条记录的标题变成 null。
成因:NoteUpdate 里所有字段都可选,如果直接用 model_dump()(不带参数),没传的字段会以默认值 None 出现在结果里,note.update(changes) 就把它们全写成了 null。
修法:两个动作配套。① model_dump(exclude_unset=True) —— 只输出"请求里真的出现过的字段";② 给 title/content 加 field_validator,显式传 null 时直接 422:
{"detail":[{"type":"value_error","loc":["body","title"],
"msg":"Value error, 不想改就别传这个字段;传了就必须是字符串","input":null}]}
exclude_unset 是 PATCH 的标配,忘了它,"只改一个字段"就会变成"把其他字段全清空"——这类 bug 在测试环境很难发现,因为测试数据往往每个字段都有值。
本章验收
- 五个端点全部跑通,
curl分别拿到 200 / 201 / 200 / 200 / 204 -
/docs里能用Try it out成功新建一条,也能故意触发一次 422 -
/openapi.json里能看到201与422两种响应声明 - 能说出
response_model的两件事:裁剪输出、生成文档 - 能解释
exclude_unset=True解决的是什么问题 - 说得出
Depends现在省了什么、卷 6 会用它做什么
自测
Q1:response_model=Note 看起来只是"声明一下返回类型",为什么说它是安全底线?
看答案
因为它是一个输出白名单:模型里没有的字段,即使你 return 的 dict 里有,也会被裁掉。卷 6 给记录加上 user_id、给用户表加上 password_hash 之后,只要响应模型没写这两个字段,它们就发不出去。反过来,如果偷懒直接 return 内部 dict,某天加了一个敏感字段,它就会自动出现在 API 响应里,而且没有任何测试会失败——因为接口"还是能返回数据"。安全问题的可怕之处就在这:功能全对。Q2:为什么 POST 成功返回 201,而 DELETE 成功返回 204?
看答案
201 的语义是"资源已被创建",规范还建议带一个 Location 头指向新资源;所以它要有响应体,把新建的对象(含服务端生成的 id 和 created_at)交回给客户端,前端可以直接把这条插进列表而不必再查一次。204 的语义是"成功,但没有内容要给你",删除之后客户端需要的信息只是"成功了",再返回一份被删的数据没有意义。两者都是 2xx,区别在于"有没有东西要交还"。Q3:GET /api/notes/abc 返回 422。你觉得这个设计合理吗?如果产品要求"不存在的 id 一律 404",你怎么办?
看答案
合理。422 表达的是"请求本身不合法"——abc 根本不可能是 id,这跟"id=999 不存在"是两类问题,混在一起会丢掉排错线索(前端拼错 id 时你会以为是数据被删了)。如果产品坚持 404,可以把 note_id 声明成 str,在函数里自己尝试转 int,失败时抛 404;但这等于主动放弃框架的类型校验,还要自己处理所有边界。更常见的折中是:前端把 422 和 404 都渲染成"找不到这条摘录",后端保持语义清晰。下一步
五个端点能跑了,但它们的错误形状有三种:校验错是 {"detail":[...]}、业务错是 {"detail":"..."}、崩了是一整页 HTML。下一章把它们收成一个形状,并让每条日志都能追到具体请求。