FastAPI 请求校验失败默认返回什么?
查看完整题解
参考回答
直接回答
请求参数或正文验证失败时,默认常得到 422。响应包含 detail 列表,错误项通常含 loc、msg、type 等。loc 能指明失败字段来自路径、查询还是正文。
讲清原理
客户端更适合依赖约定字段和字段位置,错误文字可随框架版本或定制策略变化。对外错误格式如需定制,应避免回显敏感输入。
例子与易错点
示例发送无效正文,核对错误位置是 body 下的字段。出站响应模型不匹配是服务端问题,不能和这种输入错误混在一起。
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
class Basket(BaseModel):
quantity: int = Field(gt=0)
app = FastAPI()
@app.post("/basket")
def basket(data: Basket):
return data
with TestClient(app) as client:
result = client.post("/basket", json={"quantity": 0})
assert result.status_code == 422
field = result.json()["detail"][0]
assert field["loc"] == ["body", "quantity"] and field["type"] == "greater_than"
print(field["loc"])
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。