知识卡片
类型注解接入载荷校验
在 FastAPI 处理函数中,把请求体声明为参数并标注相应的 pydantic 模型,框架就能在进入业务处理前校验载荷。比如创建订单需要 CreateOrderSchema,缺少必填字段应被拒绝。模型定义和路由参数绑定缺一不可。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
原书出处
参考来源
- 位置:《Microservice APIs》第 2 章《A basic API implementation》(源文件:_epub-src/OEBPS/Text/02.htm)
- 结论依据:2.5 节明确说明通过函数参数接收请求体,再以 pydantic 模型类型注解启用校验;随后的 POST 订单示例和缺字段试验展示其效果。
- 原始内容:We intercept request payloads by declaring them as a parameter of the view function, and to validate them we set their type to the relevant pydantic model. ... We intercept a payload by declaring it as a parameter in our function, and we use type hints to validate it.