Lesson 2
Types, Properties, and Required Fields
Model object shapes with `type`, `properties`, `required`, and nested schemas.
Most everyday schemas start with objects. JSON objects become useful contracts when you describe their properties and decide which fields are required.
{
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" },
"profile": {
"type": "object",
"properties": {
"displayName": { "type": "string" }
},
"required": ["displayName"]
}
},
"required": ["email", "profile"]
}
type
The type keyword can describe JSON primitives and containers:
objectarraystringnumberintegerbooleannull
Use integer only when fractional values are invalid. Use number for decimals such as prices, coordinates, and ratios.
properties
properties maps field names to schemas. Each property can have its own type and nested constraints.
Nested objects should be modeled deliberately. If a nested value has meaningful fields, give it its own schema block rather than leaving it as a generic object.
required
required is an array of property names that must be present. A common mistake is thinking every property listed under properties is automatically required. It is not.
This means you can describe optional fields without forcing clients to send them:
{
"type": "object",
"properties": {
"title": { "type": "string" },
"subtitle": { "type": "string" }
},
"required": ["title"]
}
Required does not mean non-empty
A required string can still be empty unless you add minLength.
{ "type": "string", "minLength": 1 }
Think of required as a presence rule. Think of constraints such as minLength, minimum, and pattern as value rules.