返回主题:Python Web API 框架实践

知识卡片

普通读书笔记卡 · 3462.h

出站响应也要按模型验证

理解等级:中级

请求验过还不够,服务端返回的载荷也可能缺字段或格式错误。在书中 FastAPI 示例中,路由的 response_model 用 pydantic 模型验证出站数据;额外字段会被移除,缺少必填字段会报错。客户端依赖的是响应契约,不是服务端对象原貌。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    原书出处

    参考来源

    - 位置:《Microservice APIs》第 2 章《A basic API implementation》(源文件:_epub-src/OEBPS/Text/02.htm) - 结论依据:2.6 节指出畸形响应是集成失败来源,建议发送前验证;示例通过 response_model 挂载模型,并展示额外字段过滤与必填字段缺失的错误。 - 原始内容:Malformed response payloads are a common source of API integration failures. You can avoid this problem by validating your response payloads before they leave the server. In FastAPI, this is easily done by setting the response_model parameter of a route decorator. ... FastAPI will raise an error if a required property is missing from a response payload. It will also remove any properties that are not part of the schema, and it will try to cast each property into the right type.