API development often involves dynamically constructing JSON/XML responses, which can lead to inconsistencies, missing fields, and unpredictable structures. A JSON Document introduces a structured approach to specifying the expected structure of JSON Views - similar to how an HTML Document specifies the expected structure for HTML Views. With built-in support for JSON Schema validation, this library ensures that both incoming requests and outgoing responses adhere to a predefined structure, producing a self-documenting API.
By treating JSON as a modular, manipulatable document, JsonDocument allows API developers to work with default response templates, modify them programmatically, and output consistent, schema-safe responses in JSON - or automatically translated into XML.
Schema document (api/product.json
)
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"oneOf": [
{ "$ref": "#/$defs/request" },
{ "$ref": "#/$defs/response" }
],
"$defs": {
"request": {
"type": "object",
"properties": {
"id": { "type": "integer" }
},
"required": ["id"],
"additionalProperties": false
},
"response": {
"type": "object",
"properties": {
"title": {
"type": "string"
},
"status": {
"type": "string",
"enum": [
"IN_STOCK",
"OUT_OF_STOCK",
"BACK_ORDER"
]
},
"categories": {
"type": "array",
"items": {
"type": "string",
"enum": [
"PHONE",
"LAPTOP",
"TELEVISION",
"AUDIO",
"LIGHTING"
]
},
"minItems": 1,
"uniqueItems": true
}
},
"required": [
"title",
"status",
"categories"
],
"additionalProperties": false
}
}
}
Validating the request and response in PHP: (api/product.php
):
function example(JsonDocument $json, Input $input):void {
}