hkarlstrom/openapi-validation-middleware

PSR-7 and PSR-15 OpenAPI Validation Middleware

0.5.5 2023-10-10 11:26 UTC

README

PSR-7 and PSR-15 OpenAPI Validation Middleware

The middleware parses an OpenAPI definition document (openapi.json or openapi.yaml) and validates:

  • Request parameters (path, query)
  • Request body
  • Response body

The middleware can be used with any framework using PSR-7 and PSR-15 style middlewares.

All testing has been done using Slim Framework. The tests are done with a openapi.json file that is valid according to Swagger/OpenAPI CLI

Installation

It's recommended that you use Composer to install.

composer require hkarlstrom/openapi-validation-middleware

Use Swagger/OpenAPI CLI to validate openapi.json/openapi.yaml file, as the middleware assumes it to be valid.

Usage

Basic usage with Slim Framework.

$config = [
    'settings' => [
        'determineRouteBeforeAppMiddleware' => true,
    ],
];
$app = new \Slim\App($config);
$app->add(new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json'));

Basic usage with Zend Expressive.

$app = $container->get(\Zend\Expressive\Application::class);
$app->pipe(new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json'));

Options

The options array is passed to the middleware when it's constructed.

$app = new Slim\App;
$app->add(new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json'),[
    'additionalParameters' => true,
    'stripResponse' => true
]);

beforeHandler

If defined, the function is called when the request validation fails before the next incoming middleware is called. You can use this to alter the request before passing it to the next incoming middleware in the stack. If it returns anything else than \Psr\Http\Message\ServerRequestInterface an exception will be thrown. The array $errors is an array containing all the validation errors.

$options = [
    'beforeHandler' => function (\Psr\Http\Message\ServerRequestInterface $request, array $errors) : \Psr\Http\Message\ServerRequestInterface {
        // Alter request
        return $request
    }
];

errorHandler

If defined, the function is called instead of the default error handler. If it returns anything else than Psr\Http\Message\ResponseInterface it will fallback to the default error handler.

$options = [
    'errorHandler' => function (int $code, string $message, array $errors) : \Psr\Http\Message\ResponseInterface {
        // Alter request
        return $request
    }
];

validateSecurity

If defined, the callback can return Psr\Http\Message\ResponseInterface if the operation is not allowed. $type can be none, http or apiKey.

$options = [
    'validateSecurity' => function (ServerRequestInterface $request, string $type, string $token = '', ?array $scopes) : ?\Psr\Http\Message\ResponseInterface {
        // if user is authorized
        return null;

        // create and return error response
        $response = new Response( ... );
        return $response;
    }
];

Formats

There are two ways to validate formats not defined in the OAS specification. You can implement a custom format validator and add it to the middleware, or use the build in support for the Respect Validation libray.

Custom validator

class MyOwnFormat implements Opis\JsonSchema\Format {
    public function validate($data) : bool
    {
        // Validate data
        // $isValid = ...
        return $isValid;
    }
}

$mw = new HKarlstrom\Middleware\OpenApiValidation('/path/to/openapi.json');
$mw->addFormat('string','my-own-format',new MyOwnFormat());
$app->add($mw);

Respect Validation

You can use all the validators just by setting the format property in your openapi.json/openapi.yaml file.

"schema":{
    "type" : "string",
    "format": "country-code"
}

The country-code value will resolve to the v::countryCode() validator.

You can also pass arguments to the validator defined in the format attribute:

"schema": {
    "type": "string",
    "format":"ends-with('@gmail.com')"
}

or

"schema": {
    "type": "integer",
    "format":"between(10, 20)"
}

License

The OpenAPI Validation Middleware is licensed under the MIT license. See License File for more information.