basilicom/json-schema-request-validator-bundle

Easily validate Symfony request bodies via JSON schema and automatically reject invalid requests

v2.0.1 2021-11-17 16:07 UTC

This package is auto-updated.

Last update: 2024-12-17 23:05:58 UTC


README

Easily validate Symfony request bodies via JSON schema and automatically reject invalid requests

Version

Installation

via composer

composer require basilicom/json-schema-request-validator-bundle

add to \App\Kernel

$collection->addBundle(new JsonSchemaRequestValidatorBundle());

Usage

The controller needs to implement the JsonSchemaRequestValidationControllerInterface. All request bodies of its actions then will be validated with JSON schema files set via the interface method setJsonSchemaFilePathsInFilePathProvider(FilePathProvider $filePathProvider).

All actions of this controller must have a JSON schema file which must be mapped via the route name.

The system automatically rejects an invalid incoming requests with status code "400 Bad Request". If no JSON schema file can be found it will respond with "500 Internal Server Error".

Example Symfony controller

<?php

namespace AppBundle\Controller;

use Basilicom\JsonSchemaRequestValidator\Controller\JsonSchemaRequestValidationControllerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class TestingEndpointsController extends AbstractController implements JsonSchemaRequestValidationControllerInterface
{
    /**
     * @Route("/testing", methods={"POST"}, name="testing_post")
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function testingPost(Request $request): JsonResponse
    {
        return new JsonResponse(['success']);
    }
    
    /**
     * @Route("/testing", methods={"GET"}, name="testing_get")
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function testingGet(Request $request): JsonResponse
    {
        return new JsonResponse(['success']);
    }

    public function setJsonSchemaFilePathsInFilePathProvider(FilePathProvider $filePathProvider)
    {
        $filePathProvider->setIgnoreRouteName('testing_get', true);
        $filePathProvider->setJsonSchemaFilePathForRouteName('testing_post', __DIR__ . '/../Resources/jsonschemas/test.json');
    }
}