[ADP-754] OpenAPI: JSON Schema
Overview
The OpenAPI specification defines many common formats for validation. However, there are cases not covered by the default OpenAPI schema. In these situations, custom JSON Schema can be used to define specific formats for field values, ensuring comprehensive validation and consistency across your API.
Guidance
- SHOULD use JSON Schema to define formats out of scope from OpenAPI schema
- SHOULD define custom JSON Schema on demand
- MUST follow ADP-701 for property design when creating custom schemas
- SHOULD use ADP-704 conventions for ID fields in custom schemas
- MUST adhere to ADP-24 versioning principles when updating schemas
Examples
Example 1: Defining a Country Code
Country codes are often represented using ISO 3166-1 alpha-2 format. Here's how you can define a country code using JSON Schema:
{
"type": "string",
"pattern": "^[A-Z]{2}$",
"description": "ISO 3166-1 alpha-2 country code"
}This schema defines a country code as a string consisting of exactly two uppercase letters.
Example 2: Defining a Language Code
Language codes are typically represented using ISO 639-1 format. Here's how you can define a language code using JSON Schema:
{
"type": "string",
"pattern": "^[a-z]{2}$",
"description": "ISO 639-1 language code"
}This schema defines a language code as a string consisting of exactly two lowercase letters.
JSON Schema Basics
Types
JSON Schema supports several data types, including:
stringnumberintegerbooleanarrayobjectnull
Defining Properties
A JSON object is described by defining its properties. For example:
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer",
"minimum": 0
}
},
"required": ["name"]
}In this schema:
typespecifies that the data should be an object.propertiesdefines the expected properties of the object.requiredindicates that thenameproperty must be present.
Arrays
Arrays can be defined to specify the type of items they contain:
{
"type": "array",
"items": {
"type": "string"
}
}This schema specifies that the array should contain only string items.
Nested Objects
JSON Schema can define nested objects and arrays to represent complex data structures:
{
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uuid"
},
"address": {
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
}
},
"required": ["street", "city"]
}
},
"required": ["id", "address"]
}In this example, the address property is itself an object with street and city properties.
Advanced Features
- Patterns: Enforce specific formats using regular expressions.
- Enums: Define a set of valid values for a property.
- Combining Schemas: Use
allOf,anyOf,oneOf, andnotto combine or restrict schemas.