知识卡片
未知字段可配置拒绝
若契约要求尽早暴露客户端拼写错误,可把请求模型设为拒绝未声明字段。书中 pydantic 示例在模型 Config 中设 extra = Extra.forbid,让 quantit 这类字段触发 422,而非被默默丢弃。具体配置写法应以所用 pydantic 版本核对。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
原书出处
参考来源
- 位置:《Microservice APIs》第 6 章《Building REST APIs with Python》(源文件:_epub-src/OEBPS/Text/06.htm)
- 结论依据:原文将模型 Config 的 extra 设为 forbid 后,再用拼错字段的请求展示 FastAPI 返回额外字段不允许的 422。
- 原始内容:To disallow unknown attributes, we need to define a Config class within our models and set the extra property to forbid . ... After running this test, you’ll see that now FastAPI invalidates this payload and returns a helpful 422 response with the following message: “ extra fields not permitted .”