required vs. default in JSON Schema: which keyword should own missing-field handling?
0 reputation · 30 May 2021, 23:22 UTC
0 reputation · 30 May 2021, 23:22 UTC
JSON Schema offers two documented mechanisms for fields that downstream processing expects to always exist: the required keyword, which fails validation when a property is absent, and the default keyword, which supplies a fallback value. Deciding which one owns completeness guarantees is the core design choice.
Under the draft-07 through 2020-12 meta-schemas, required is a validation assertion, while default is annotation-only metadata — the specification does not require validators to inject defaults into validated data. Implementations differ: some can be configured to apply defaults, others ignore them entirely. The specification also does not define precedence when a property is both required and defaulted, so behavior for a missing field may vary by tool.
Open questions:
required, or left out of required and given a default instead?required and default on the same property a meaningful pattern, or does it depend on unspecified behavior?default be treated purely as documentation rather than a runtime mechanism?35275 reputation · 31 May 2021, 00:51 UTC
required keyword. The default keyword should be treated as documentation or a hint for specific tools, as the JSON Schema specification does not mandate that validators inject these values into the validated data.
The primary distinction between these two keywords is the difference between validation and annotation.
The required keyword is a validation assertion. If a property listed in the required array is missing from the input, the validation fails. This is the only way to guarantee that your downstream code will receive the field based solely on the JSON Schema specification itself.
Under the current JSON Schema meta-schemas (from draft-07 through 2020-12), the default keyword is technically metadata. It describes what the value should be if the field is absent, but the specification does not require a validator to modify the input data to insert that value. While some libraries (like Ajv in JavaScript) offer a configuration flag to "apply defaults," this is an implementation-specific behavior rather than a standard.
required when: The field is critical for the application logic, and its absence should result in an error response or a rejected request.default when: You want to provide a hint to human readers, or you are using a specific tool that supports automatic population, but the application does not strictly need the field to function.If your goal is completeness guarantees, rely on required. If your goal is to provide a fallback for documentation or specialized tools, use default, but ensure your code handles the case where the field might still be missing.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.