1. Why JSON Schema is Essential for Modern APIs
As microservices and frontend applications exchange vast amounts of structured data, ensuring payload integrity becomes critical. JSON Schema is an IETF standard that provides a clear vocabulary to annotate and validate JSON documents.
2. Core Building Blocks of a JSON Schema
Let's dissect a standard user registration schema:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UserRegistration",
"type": "object",
"required": ["userId", "email", "age", "role"],
"properties": {
"userId": {
"type": "string",
"format": "uuid"
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 18,
"maximum": 120
},
"role": {
"type": "string",
"enum": ["admin", "developer", "viewer"]
},
"tags": {
"type": "array",
"items": { "type": "string" },
"uniqueItems": true
}
},
"additionalProperties": false
}
3. Advanced Validation Techniques
A. String Formats and Regular Expressions
Use pattern for custom regex matching (such as phone numbers or postal codes) and format for standard formats (date-time, ipv4, uri, email).
B. Conditional Logic with if/then/else
JSON Schema supports conditional validation. For example, if a user selects payment method 'CREDIT_CARD', require the 'cardNumber' field:
{
"if": {
"properties": { "paymentType": { "const": "CREDIT_CARD" } }
},
"then": {
"required": ["cardNumber", "cvv"]
}
}