Search by

nayzo / json-schema-validator-bundle

nayzo

Validate Symfony HTTP requests and responses against OpenAPI 3.0 contracts

Package info

github.com/nayzo/json-schema-validator-bundle

Type:symfony-bundle

pkg:composer/nayzo/json-schema-validator-bundle

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v2.0.0 2026-11-29 14:18 UTC

This package is auto-updated.

Last update: 2026-11-29 14:19:10 UTC


README

tests Total Downloads Latest Stable Version

Validate Symfony requests and responses against your OpenAPI 3.0 contract, so invalid input stays out of your controllers and changes to your API output are caught early.

Which version do I need?

Your application Bundle version Install
Symfony 6.4, 7 or 8 2 composer require nayzo/json-schema-validator-bundle:^2.0
Symfony 5.4 to 6.3 1 composer require nayzo/json-schema-validator-bundle:^1.0

Both versions require PHP 8.1 or later. Symfony itself may require a newer PHP version.

The documentation for version 1 is on the 1.x branch. Upgrading? See UPGRADE-2.0.md.

Installation

composer require nayzo/json-schema-validator-bundle:^2.0

If Symfony Flex registers the bundle, you can go straight to configuration. Otherwise, add it to config/bundles.php:

return [
    // ...
    Nayzo\JsonSchemaValidatorBundle\JsonSchemaValidatorBundle::class => ['all' => true],
];

Validate an endpoint

1. Write the contract

For an order_create route that handles POST /orders, save this as config/openapi/orders.yaml:

openapi: 3.0.3
info:
    title: Orders API
    version: '1.0'
paths:
    /orders:
        post:
            requestBody:
                required: true
                content:
                    application/json:
                        schema:
                            type: object
                            required: [quantity]
                            properties:
                                quantity: { type: integer, minimum: 1 }
            responses:
                '201':
                    description: Order created
                    content:
                        application/json:
                            schema:
                                type: object
                                required: [id]
                                properties:
                                    id: { type: integer }

2. Enable validation for the contract

# config/packages/nayzo_json_schema_validator.yaml
nayzo_json_schema_validator:
    resources:
        orders:
            contract_file_path: '%kernel.project_dir%/config/openapi/orders.yaml'
            enable_default_request_validation_subscriber: true
            enable_default_response_validation_subscriber: true
    enable_default_validation_exception_subscriber: true

3. Select the requests to validate

Give the resource a support service. The service name is arbitrary; getResourceName() selects the contract, and support() decides whether to validate the current request.

namespace App\Validator;

use Nayzo\JsonSchemaValidatorBundle\Configurator\ValidationSubscriberSupportInterface;
use Symfony\Component\HttpFoundation\RequestStack;

final class OrderValidationSupport implements ValidationSubscriberSupportInterface
{
    public function __construct(private readonly RequestStack $requestStack)
    {
    }

    public static function getResourceName(): string
    {
        return 'orders';
    }

    public function support(): bool
    {
        return 'order_create' === $this->requestStack->getCurrentRequest()?->attributes->get('_route');
    }
}

Load this class as an autowired, autoconfigured service. If your application does not use autoconfiguration, tag the service with nayzo.json_schema_validator.support. Use one support service per resource with enabled subscribers. If there is no support service, those subscribers do not validate anything.

A JSON request such as {"quantity":2} reaches the controller. A response such as {"id":42} with status 201 matches the contract. A request with {"quantity":"two"} is rejected before the controller runs.

What happens when validation fails?

With the default exception subscriber enabled:

Failure HTTP status JSON body
Request does not match 422 by default {"error":{"message":"Request does not match the OpenAPI contract."}}
Response does not match 500 {"error":{"message":"Response does not match the OpenAPI contract."}}

The built-in validation subscribers only validate main requests. Response validation skips responses sent before the controller stage, such as a 401 from an authentication listener, as well as responses generated by exception handlers and Symfony streamed and binary file responses. A 4xx returned directly by a selected controller must still match the contract.

Leave the default exception subscriber disabled to handle ValidationException in your own kernel.exception listener. ResponseValidationException extends it and identifies an invalid response. The original exception from the OpenAPI validator is available through getPrevious() for server-side diagnostics. Keep its message out of client responses.

Use the validator directly

Disable the corresponding default subscribers when validating from your own service or event subscriber. Inject ValidatorFactory and select a contract with #[Target]. For a resource named back_office, the target is backOfficeContract.

namespace App\Validator;

use Nayzo\JsonSchemaValidatorBundle\Contract\JsonSchemaValidatorContractInterface;
use Nayzo\JsonSchemaValidatorBundle\Validator\ValidatorFactory;
use Symfony\Component\DependencyInjection\Attribute\Target;
use Symfony\Component\HttpFoundation\Request;

final class OrderRequestValidator
{
    public function __construct(
        #[Target('ordersContract')]
        private readonly JsonSchemaValidatorContractInterface $contract,
        private readonly ValidatorFactory $validatorFactory,
    ) {
    }

    public function validate(Request $request): void
    {
        $validator = $this->validatorFactory->build($this->contract->getContractFile());
        $validator->validate($request, $request->getPathInfo(), $request->getMethod());
    }
}

validate() accepts Symfony requests and buffered responses, as well as PSR-7 server requests and responses. It returns true on success and throws on failure. Pass the actual request path and HTTP method with either message; use the request's path and method when validating its response.

Configuration reference

nayzo_json_schema_validator:
    resources: {}                                      # OpenAPI contracts keyed by resource name
    # resources:
    #     orders:
    #         contract_file_path: '%kernel.project_dir%/config/openapi/orders.yaml' # required per resource
    #         enable_default_request_validation_subscriber: false                 # validate before the action
    #         enable_default_response_validation_subscriber: false                # validate before sending
    enable_default_validation_exception_subscriber: false    # convert validation failures to JSON responses
    validation_exception_status_code: 422                    # 400 to 499, for invalid requests only

Use a readable local OpenAPI 3.0 file in YAML or JSON (.json). The file is opened when the validator is built, so an unused contract does not have to be available when Symfony compiles the container. Check that each file can be opened in the deployed application.

Security

  • Use contracts and $ref targets you trust. Keep contract paths in application configuration, not in request parameters.
  • Choose the support predicate carefully. An endpoint the predicate does not select is not validated.
  • Contract validation complements authentication, authorization and application-level rules. It does not replace them.
  • Send generic error messages to clients. Upstream diagnostics can contain request or response data; restrict who can see them and redact sensitive values before logging them.

License

This bundle is under the MIT license. See LICENSE.