Master JSON Schema in PHP: Validate Your Data with Confidence
This guide explains what JSON Schema is, its core components, and how to use the PHP library justinrainbow/json-schema to install, validate data, coerce types, apply defaults, handle inline references, configure validation flags, and run tests for robust API development.
What Is JSON Schema?
JSON Schema is a specification for describing and validating the structure of JSON data. It can enforce types, constraints, and required fields while also serving as documentation for the data format.
Structure of a JSON Schema
Keywords : Define validation rules such as required, type, properties, minimum, etc.
Schema Instance : A JSON object that describes the data to be validated, including property names, types, and value ranges.
Metadata : Information about the schema itself, like title, description, and id. Metadata is not used for validation but helps understand the schema.
Using JSON Schema in PHP
The justinrainbow/json-schema package implements the Draft‑3 and Draft‑4 specifications for PHP.
Installation
composer require justinrainbow/json-schemaBasic Validation Example
<?php
$data = json_decode(file_get_contents('data.json'));
$validator = new JsonSchema\Validator;
$validator->validate($data, (object)['$ref' => 'file://' . realpath('schema.json')]);
if ($validator->isValid()) {
echo "The supplied JSON validates against the schema.
";
} else {
echo "JSON does not validate. Violations:
";
foreach ($validator->getErrors() as $error) {
printf("[%s] %s
", $error['property'], $error['message']);
}
}Type Coercion
If you receive data via HTTP, you can coerce strings and booleans to the types defined in your schema.
<?php
use JsonSchema\SchemaStorage;
use JsonSchema\Validator;
use JsonSchema\Constraints\Factory;
use JsonSchema\Constraints\Constraint;
$request = (object)[
'processRefund' => "true",
'refundAmount' => "17"
];
$validator->validate(
$request,
(object)[
"type" => "object",
"properties" => (object)[
"processRefund" => (object)["type" => "boolean"],
"refundAmount" => (object)["type" => "number"]
]
],
Constraint::CHECK_MODE_COERCE_TYPES
);
is_bool($request->processRefund); // true
is_int($request->refundAmount); // trueYou can also use the shortcut method:
$validator->coerce($request, $schema);
// Equivalent to validate(..., Constraint::CHECK_MODE_COERCE_TYPES)Applying Default Values
If a schema defines defaults, the validator can automatically insert them during validation.
<?php
use JsonSchema\Validator;
use JsonSchema\Constraints\Constraint;
$request = (object)['refundAmount' => 17];
$validator = new Validator();
$validator->validate(
$request,
(object)[
"type" => "object",
"properties" => (object)[
"processRefund" => (object)["type" => "boolean", "default" => true]
]
],
Constraint::CHECK_MODE_APPLY_DEFAULTS
);
is_bool($request->processRefund); // trueUsing Inline References
<?php
use JsonSchema\SchemaStorage;
use JsonSchema\Validator;
use JsonSchema\Constraints\Factory;
$jsonSchema = <<<'JSON'
{
"type": "object",
"properties": {
"data": {
"oneOf": [
{"$ref": "#/definitions/integerData"},
{"$ref": "#/definitions/stringData"}
]
}
},
"required": ["data"],
"definitions": {
"integerData": {"type": "integer", "minimum": 0},
"stringData": {"type": "string"}
}
}
JSON;
$jsonSchemaObject = json_decode($jsonSchema);
$schemaStorage = new SchemaStorage();
$schemaStorage->addSchema('file://mySchema', $jsonSchemaObject);
$jsonValidator = new Validator(new Factory($schemaStorage));
$jsonToValidateObject = json_decode('{"data":123}');
$jsonValidator->validate($jsonToValidateObject, $jsonSchemaObject);Configuration Flags
Constraint::CHECK_MODE_NORMAL– Default mode. Constraint::CHECK_MODE_TYPE_CAST – Enables fuzzy type checking for arrays and objects. Constraint::CHECK_MODE_COERCE_TYPES – Attempts to cast data to match the schema. Constraint::CHECK_MODE_EARLY_COERCE – Applies type coercion as early as possible. Constraint::CHECK_MODE_APPLY_DEFAULTS – Inserts default values when properties are missing. Constraint::CHECK_MODE_ONLY_REQUIRED_DEFAULTS – Applies defaults only for required fields. Constraint::CHECK_MODE_EXCEPTIONS – Throws an exception on validation failure. Constraint::CHECK_MODE_DISABLE_FORMAT – Skips format validation. Constraint::CHECK_MODE_VALIDATE_SCHEMA – Re‑validates the schema itself.
Note that CHECK_MODE_COERCE_TYPES or CHECK_MODE_APPLY_DEFAULTS will modify the original data. CHECK_MODE_EARLY_COERCE only takes effect when combined with CHECK_MODE_COERCE_TYPES.
Running Tests
composer test # run all unit tests
composer testOnly TestClass # run a specific test class
composer testOnly TestClass::testMethod # run a specific test method
composer style-check # check code style for errors
composer style-fix # automatically fix code style errorsConclusion
JSON Schema makes it easy to constrain and validate data, giving developers confidence when building APIs. In PHP, using the justinrainbow/json-schema library requires only a few lines of code to load a schema, validate data, coerce types, apply defaults, and handle references.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
