PHPackages                             hkarlstrom/openapi-validation-middleware - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. hkarlstrom/openapi-validation-middleware

ActiveLibrary[HTTP &amp; Networking](/categories/http)

hkarlstrom/openapi-validation-middleware
========================================

PSR-7 and PSR-15 OpenAPI Validation Middleware

0.5.5(2y ago)95198.8k↓15.5%18[12 issues](https://github.com/hkarlstrom/openapi-validation-middleware/issues)[1 PRs](https://github.com/hkarlstrom/openapi-validation-middleware/pulls)1MITPHPPHP ^8.1CI passing

Since Sep 24Pushed 3mo ago4 watchersCompare

[ Source](https://github.com/hkarlstrom/openapi-validation-middleware)[ Packagist](https://packagist.org/packages/hkarlstrom/openapi-validation-middleware)[ RSS](/packages/hkarlstrom-openapi-validation-middleware/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (12)Versions (38)Used By (1)

OpenAPI Validation Middleware
=============================

[](#openapi-validation-middleware)

PSR-7 and PSR-15 [OpenAPI](https://www.openapis.org/) 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](https://www.php-fig.org/psr/psr-7/) and [PSR-15](https://www.php-fig.org/psr/psr-15/) style middlewares.

All testing has been done using [Slim Framework](https://github.com/slimphp/Slim). The tests are done with a openapi.json file that is valid according to [Swagger/OpenAPI CLI](https://www.npmjs.com/package/swagger-cli)

Installation
------------

[](#installation)

It's recommended that you use [Composer](https://getcomposer.org/download) to install.

```
composer require hkarlstrom/openapi-validation-middleware
```

Use [Swagger/OpenAPI CLI](https://www.npmjs.com/package/swagger-cli) to validate openapi.json/openapi.yaml file, as the middleware assumes it to be valid.

Usage
-----

[](#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

[](#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
]);
```

typeformatdefaultdescriptionadditionalParametersboolfalseAllow additional parameters in querybeforeHandlercallablenullInstructions [below](README.md#beforehandler)errorHandlercallablenullInstructions [below](README.md#errorhandler)exampleResponseboolfalseReturn example response from openapi.json/openapi.yaml if route implementation is emptymissingFormatExceptionbooltrueThrow an exception if a format validator is missingpathNotFoundExceptionbooltrueThrow an exception if the path is not found in openapi.json/openapi.yamlsetDefaultParametersboolfalseSet the default parameter values for missing parameters and alter the request objectstrictEmptyArrayValidationboolfalseConsider empty array when object is expected as validation errorstripResponseboolfalseStrip additional attributes from response to prevent response validation errorstripResponseHeadersboolfalseStrip additional headers from response to prevent response validation errorvalidateErrorboolfalseShould the error response be validatedvalidateRequestbooltrueShould the request be validatedvalidateResponsebooltrueShould the response's body be validatedvalidateResponseHeadersboolfalseShould the response's headers be validatedvalidateSecuritycallablenullInstructions [below](README.md#validateSecurity)#### beforeHandler

[](#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

[](#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

[](#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
-------

[](#formats)

There are two ways to validate formats not defined in the [OAS](https://swagger.io/specification/#dataTypes) specification. You can implement a custom format validator and add it to the middleware, or use the build in support for the [Respect Validation](http://respect.github.io/Validation/) libray.

#### Custom validator

[](#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

[](#respect-validation)

You can use [all the validators](http://respect.github.io/Validation/docs/validators.html) 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
-------

[](#license)

The OpenAPI Validation Middleware is licensed under the MIT license. See [License File](LICENSE) for more information.

###  Health Score

53

—

FairBetter than 97% of packages

Maintenance51

Moderate activity, may be stable

Popularity49

Moderate usage in the ecosystem

Community26

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 73.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~54 days

Recently: every ~42 days

Total

35

Last Release

951d ago

PHP version history (3 changes)0.1.0PHP ^7.1

0.4PHP ^7.1||^8

0.5PHP ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/4e1d116b37e7b3cf158c9e81ac62aa84150c989ca10f878b1e77621cb93991ed?d=identicon)[hkarlstrom](/maintainers/hkarlstrom)

---

Top Contributors

[![hkarlstrom](https://avatars.githubusercontent.com/u/793063?v=4)](https://github.com/hkarlstrom "hkarlstrom (55 commits)")[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (4 commits)")[![francescozanoni](https://avatars.githubusercontent.com/u/16524243?v=4)](https://github.com/francescozanoni "francescozanoni (3 commits)")[![lezhnev74](https://avatars.githubusercontent.com/u/10206110?v=4)](https://github.com/lezhnev74 "lezhnev74 (2 commits)")[![chrisyoungbrighte](https://avatars.githubusercontent.com/u/128448021?v=4)](https://github.com/chrisyoungbrighte "chrisyoungbrighte (2 commits)")[![hatxor](https://avatars.githubusercontent.com/u/541532?v=4)](https://github.com/hatxor "hatxor (1 commits)")[![mohammed-fahad](https://avatars.githubusercontent.com/u/12007899?v=4)](https://github.com/mohammed-fahad "mohammed-fahad (1 commits)")[![paulogic](https://avatars.githubusercontent.com/u/28298476?v=4)](https://github.com/paulogic "paulogic (1 commits)")[![bvis](https://avatars.githubusercontent.com/u/580682?v=4)](https://github.com/bvis "bvis (1 commits)")[![staabm](https://avatars.githubusercontent.com/u/120441?v=4)](https://github.com/staabm "staabm (1 commits)")[![christheyounger](https://avatars.githubusercontent.com/u/2162344?v=4)](https://github.com/christheyounger "christheyounger (1 commits)")[![cia1](https://avatars.githubusercontent.com/u/7448714?v=4)](https://github.com/cia1 "cia1 (1 commits)")[![diego-ninja](https://avatars.githubusercontent.com/u/78662279?v=4)](https://github.com/diego-ninja "diego-ninja (1 commits)")[![fredcido](https://avatars.githubusercontent.com/u/7162412?v=4)](https://github.com/fredcido "fredcido (1 commits)")

---

Tags

psr-7middlewarevalidationopenapipsr-15

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/hkarlstrom-openapi-validation-middleware/health.svg)

```
[![Health](https://phpackages.com/badges/hkarlstrom-openapi-validation-middleware/health.svg)](https://phpackages.com/packages/hkarlstrom-openapi-validation-middleware)
```

###  Alternatives

[tuupola/slim-basic-auth

PSR-7 and PSR-15 HTTP Basic Authentication Middleware

4442.0M26](/packages/tuupola-slim-basic-auth)[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

1331.8M24](/packages/tuupola-cors-middleware)[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[relay/relay

A PSR-15 server request handler.

3302.1M86](/packages/relay-relay)[laminas/laminas-stratigility

PSR-7 middleware foundation for building and dispatching middleware pipelines

586.6M81](/packages/laminas-laminas-stratigility)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
