Skip to content

Schema-Safe API Endpoints with JSON/XML Views.

Notifications You must be signed in to change notification settings

PhpGt/JsonDocument

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Schema-safe API endpoints with JSON/XML views.

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.


Build status Code quality Code coverage Current version PHP.G/JsonDocument documentation

Example usage: specify schema for API request and response

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 {
	
}

About

Schema-Safe API Endpoints with JSON/XML Views.

Resources

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

 

Packages

 
 
 

Languages