Define Required Fields in YAML Schema
Learn how to specify required fields in YAML Schema definitions generated from JSON. Covers the required keyword, optional vs mandatory fields, conditional requirements, and validation behavior.
Detailed Explanation
Required Fields in YAML Schema
The required keyword in YAML Schema lists property names that must be present in a valid document. When converting from JSON, the converter typically marks all present fields as required, which you then refine based on your actual requirements.
Example JSON Input
{
"name": "web-api",
"version": "2.0.0",
"port": 3000,
"host": "0.0.0.0",
"debug": false,
"logLevel": "info"
}
Generated YAML Schema
type: object
properties:
name:
type: string
version:
type: string
port:
type: integer
host:
type: string
debug:
type: boolean
logLevel:
type: string
required:
- name
- version
- port
additionalProperties: false
Required vs Optional Fields
After generation, you decide which fields are truly required:
| Field | Required? | Rationale |
|---|---|---|
name |
Yes | Identifies the service |
version |
Yes | Needed for compatibility |
port |
Yes | Service cannot start without it |
host |
No | Defaults to 0.0.0.0 |
debug |
No | Defaults to false |
logLevel |
No | Defaults to info |
additionalProperties
Controls whether unlisted keys are allowed:
type: object
properties:
name:
type: string
additionalProperties: false # Rejects any key not in properties
additionalProperties:
type: string # Allows extra keys, but values must be strings
Conditional Requirements
Use if/then for fields that are required only under certain conditions:
properties:
database:
type: string
enum: [postgres, mysql, sqlite]
connectionString:
type: string
filePath:
type: string
if:
properties:
database:
const: sqlite
then:
required:
- filePath
else:
required:
- connectionString
Nested Required Fields
Each nested object has its own required array:
properties:
server:
type: object
properties:
host:
type: string
port:
type: integer
required:
- port
required:
- server
Here, the server object itself is required, and within it, port is required but host is optional.
Validation Behavior
When a required field is missing, the validator returns an error specifying the field path:
Error: Required property 'port' is missing at path '/server'
This precise error reporting makes it easy to identify and fix configuration issues.
Use Case
In team environments, a YAML schema with clearly defined required fields serves as living documentation for which configuration values are mandatory versus optional. This prevents deployment failures caused by missing critical settings and reduces onboarding time for new developers who can read the schema to understand the minimum viable configuration.