知识卡片

普通读书笔记卡 · 3462.g

可选字段不等于可为null

理解等级:中级

字段可选表示请求中可以省略,不表示显式传入 null 也有效。订单数量省略时可用默认值 1,但若契约禁止 null,模型就需单独校验。把“缺失”和“空值”混为一谈会让客户端与服务端对同一载荷产生不同理解。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    原书出处

    参考来源

    - 位置:《Microservice APIs》第 2 章《A basic API implementation》(源文件:_epub-src/OEBPS/Text/02.htm) - 结论依据:2.5 节明确区分 optional 与 nullable,举 quantity 默认 1 却接受 null 的例子,并给出附加验证规则来拒绝 null。 - 原始内容:In terms of API integrations, optional isn’t quite the same as nullable: a property can be optional because it has a default value, but that doesn’t mean it can be null . To enforce the right behavior in pydantic, we need to include an additional validation rule that prevents users from setting the value of quantity to null .