Fundamentals 8 min read

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.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Master JSON Schema in PHP: Validate Your Data with Confidence

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-schema

Basic 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);   // true

You 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); // true

Using 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 errors

Conclusion

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJSON SchemaPHPdata validationschema validation
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.