PHPackages                             mimosafa/laravel-openapi-validation-helper - 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. [Testing &amp; Quality](/categories/testing)
4. /
5. mimosafa/laravel-openapi-validation-helper

ActiveLibrary[Testing &amp; Quality](/categories/testing)

mimosafa/laravel-openapi-validation-helper
==========================================

A helper trait for Laravel to transparently validate that an application's API conforms to its OpenAPI specification during feature tests.

1.1.0(6mo ago)05MITPHP

Since Oct 21Pushed 6mo agoCompare

[ Source](https://github.com/mimosafa/laravel-openapi-validation-helper)[ Packagist](https://packagist.org/packages/mimosafa/laravel-openapi-validation-helper)[ Docs](https://github.com/mimosafa/laravel-openapi-validation-helper)[ RSS](/packages/mimosafa-laravel-openapi-validation-helper/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (6)Versions (3)Used By (0)

Laravel OpenAPI Validation Helper
=================================

[](#laravel-openapi-validation-helper)

[日本語のREADMEはこちら](README.ja.md)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ff5b10e15483d61e370eba6e19e94bf341d795c20deddde3b80b3023a9325df8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d696d6f736166612f6c61726176656c2d6f70656e6170692d76616c69646174696f6e2d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mimosafa/laravel-openapi-validation-helper)[![Total Downloads](https://camo.githubusercontent.com/b146b8daf502a8dfacb2808aaac1c6eda987ea81f6faa07a0fa9c267403cffe4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d696d6f736166612f6c61726176656c2d6f70656e6170692d76616c69646174696f6e2d68656c7065722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mimosafa/laravel-openapi-validation-helper)

This library provides a helper for transparently validating HTTP requests and responses against an OpenAPI 3.0 schema in Laravel feature tests. It automatically runs validations during your test runs, allowing you to constantly check for discrepancies between your API specification and its implementation.

Features
--------

[](#features)

- **Transparent Validation**: Utilizes the `RequestHandled` event to introduce validation with almost no changes to your existing test code.
- **Flexible Control**: Easily enable or disable request/response validation on a per-test basis.
- **API Prefix Support**: Handles URL prefixes like `/api` separately from the schema definition.
- **Easy Setup**: Get started by simply using a trait in your `TestCase` and implementing a few methods.
- **Detailed Error Reporting**: Outputs detailed messages on validation failure, indicating which part of the specification was violated.

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

[](#installation)

Install via Composer.

```
composer require mimosafa/laravel-openapi-validation-helper --dev
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

#### 1. Use the Trait

[](#1-use-the-trait)

Use the `TestCaseHelper` trait in your base test case (usually `tests/TestCase.php`) or in individual test classes.

```
// tests/TestCase.php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use LaravelOpenAPIValidationHelper\TestCaseHelper;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    use TestCaseHelper; // Add this trait
}
```

#### 2. Call the Setup Method

[](#2-call-the-setup-method)

In your test class's `setUp()` method, call `setUpTransparentlyTest()`.

```
protected function setUp(): void
{
    parent::setUp();
    $this->setUpTransparentlyTest(); // Call this method
}
```

#### 3. Implement Required Methods

[](#3-implement-required-methods)

Implement the three required abstract methods for validation. It is often convenient to define properties in the test class and override their values in each test method to set them dynamically.

```
// tests/Feature/ExampleTest.php

namespace Tests\Feature;

use LaravelOpenAPIValidationHelper\HttpRequestMethod;
use League\OpenAPIValidation\PSR7\ValidatorBuilder;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    // Set these properties in each test method
    protected string $path = '/users/1';
    protected HttpRequestMethod $operation = HttpRequestMethod::GET;

    protected function path(): string
    {
        return $this->path;
    }

    protected function operation(): HttpRequestMethod
    {
        return $this->operation;
    }

    protected function getValidatorBuilder(): ValidatorBuilder
    {
        // Specify the path to your openapi.yml
        return (new ValidatorBuilder)->fromYamlFile(base_path('tests/openapi.yml'));
    }

    protected function setUp(): void
    {
        parent::setUp();
        $this->setUpTransparentlyTest();
    }

    /** @test */
    public function a_user_can_be_retrieved(): void
    {
        // Set properties
        $this->path = '/users/1';
        $this->operation = HttpRequestMethod::GET;

        // Method and URI can be omitted (automatically retrieved from operation() and path())
        $response = $this->json();
        $response->assertStatus(200);

        // Or you can explicitly specify them as before
        // $response = $this->getJson('/users/1');
    }
}
```

#### 4. When API Prefix is Needed

[](#4-when-api-prefix-is-needed)

If your application routes have a prefix like `/api/users`, override the `prefix()` method.

```
class ExampleTest extends TestCase
{
    protected string $path = '/users/1';
    protected HttpRequestMethod $operation = HttpRequestMethod::GET;

    // Override the method to return the prefix
    protected function prefix(): string
    {
        return '/api';
    }

    protected function path(): string
    {
        return $this->path;
    }

    protected function operation(): HttpRequestMethod
    {
        return $this->operation;
    }

    protected function getValidatorBuilder(): ValidatorBuilder
    {
        return (new ValidatorBuilder)->fromYamlFile(base_path('tests/openapi.yml'));
    }

    protected function setUp(): void
    {
        parent::setUp();
        $this->setUpTransparentlyTest();
    }

    /** @test */
    public function a_user_can_be_retrieved(): void
    {
        $this->path = '/users/1';
        $this->operation = HttpRequestMethod::GET;

        // Request to /api/users/1, validated against schema /users/{id}
        $response = $this->json();
        $response->assertStatus(200);
    }
}
```

How it Works
------------

[](#how-it-works)

This library does not perform validation directly. Instead, it delegates the core validation logic to the `league/openapi-psr7-validator` package. The division of responsibilities is as follows:

### The `TestCaseHelper` Trait (This Library)

[](#the-testcasehelper-trait-this-library)

- Acts as a **"bridge"**.
- It captures the HTTP request and response executed within a Laravel test.
- It converts them into the PSR-7 standard format that `league/openapi-psr7-validator` can understand.
- During this conversion, it strips any defined prefix (like `/api`) to align the path with the OpenAPI schema.
- It then hands over the prepared request and response to the validation engine.

### The `league/openapi-psr7-validator` Package

[](#the-leagueopenapi-psr7-validator-package)

- Acts as the **"validation engine"**.
- It reads the `openapi.yml` file and fully understands the API specification.
- It automatically determines which schema template (e.g., `/users/{id}`) corresponds to the concrete path of the request (e.g., `/users/456`) passed from `TestCaseHelper`.
- Based on the matched schema definition, it rigorously checks if the request and response contents (parameters, body, headers, etc.) comply with the specification.

This collaboration allows developers to transparently test for OpenAPI specification compliance simply by writing their Laravel tests as they normally would.

API
---

[](#api)

### Required Methods

[](#required-methods)

#### `path(): string`

[](#path-string)

Returns the OpenAPI schema path for the current test.

```
protected function path(): string
{
    return '/users/{id}'; // or a concrete value like '/users/1'
}
```

#### `operation(): HttpRequestMethod`

[](#operation-httprequestmethod)

Returns the HTTP method to validate for the current test.

```
protected function operation(): HttpRequestMethod
{
    return HttpRequestMethod::GET;
}
```

#### `getValidatorBuilder(): ValidatorBuilder`

[](#getvalidatorbuilder-validatorbuilder)

Returns a `ValidatorBuilder` instance loaded with your OpenAPI schema.

```
protected function getValidatorBuilder(): ValidatorBuilder
{
    return (new ValidatorBuilder)->fromYamlFile(base_path('tests/openapi.yml'));
}
```

### Optional Methods

[](#optional-methods)

#### `prefix(): string`

[](#prefix-string)

Returns the application's routing prefix. Defaults to an empty string. Override this method only if your application uses a prefix.

```
protected function prefix(): string
{
    return '/api'; // Default is '' (empty string)
}
```

### Validation Control Methods

[](#validation-control-methods)

#### `ignoreRequestCompliance()`

[](#ignorerequestcompliance)

Temporarily disables request validation for the current test.

```
public function test_with_invalid_request(): void
{
    $this->ignoreRequestCompliance();

    // Request validation will not run even for an invalid request
    $this->postJson('/api/users', []);
}
```

#### `ignoreResponseCompliance()`

[](#ignoreresponsecompliance)

Temporarily disables response validation for the current test.

```
public function test_with_invalid_response(): void
{
    $this->ignoreResponseCompliance();

    // Response validation will not run
    $this->postJson('/api/users', ['generate_invalid_response' => true]);
}
```

### HTTP Request Methods

[](#http-request-methods)

The `TestCaseHelper` trait overrides the `json()` and `call()` methods to automatically set default values when arguments are omitted.

#### `json($method = '', $uri = '', array $data = [], array $headers = [], $options = 0)`

[](#jsonmethod---uri---array-data---array-headers---options--0)

When HTTP method and URI are omitted, they are automatically retrieved from `operation()` and `prefix() . path()`.

```
// Shorthand (recommended)
$this->json(); // Uses operation() and prefix() . path()

// Explicit specification also possible
$this->json('GET', '/api/users/1');
$this->getJson('/api/users/1'); // Traditional usage still works
```

#### `call($method = '', $uri = '', $parameters = [], $cookies = [], $files = [], $server = [], $content = null)`

[](#callmethod---uri---parameters---cookies---files---server---content--null)

Like `json()`, HTTP method and URI are automatically set to default values when omitted.

```
// Shorthand
$this->call(); // Uses operation() and prefix() . path()

// Explicit specification also possible
$this->call('POST', '/api/users', ['name' => 'John']);
```

Acknowledgements
----------------

[](#acknowledgements)

This library was heavily inspired by the development blog post "[LaravelアプリケーションのAPIがSwagger/OpenAPIドキュメントに準拠していることを透過的にテストする](https://nextat.co.jp/staff/archives/253)" by 株式会社Nextat（ネクスタット）.

I would like to express my deep gratitude to the author for publishing such a wonderful idea and implementation hints.

License
-------

[](#license)

This library is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance66

Regular maintenance activity

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% 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 ~1 days

Total

2

Last Release

201d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/05236b7ac278d43c29071b254598c325a110d855f3a57f869dc80201437a1270?d=identicon)[mimosafa](/maintainers/mimosafa)

---

Top Contributors

[![mimosafa](https://avatars.githubusercontent.com/u/1770470?v=4)](https://github.com/mimosafa "mimosafa (5 commits)")

---

Tags

testinglaravelvalidationswaggeropenapi

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mimosafa-laravel-openapi-validation-helper/health.svg)

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

###  Alternatives

[osteel/openapi-httpfoundation-testing

Validate HttpFoundation requests and responses against OpenAPI (3+) definitions

1201.9M6](/packages/osteel-openapi-httpfoundation-testing)[kirschbaum-development/laravel-openapi-validator

Automatic OpenAPI validation for Laravel HTTP tests

581.1M5](/packages/kirschbaum-development-laravel-openapi-validator)[hotmeteor/spectator

Testing helpers for your OpenAPI spec

3021.4M1](/packages/hotmeteor-spectator)[spurwork/spectator

Testing helpers for your OpenAPI spec

3021.5k](/packages/spurwork-spectator)[guanguans/laravel-soar

SQL optimizer and rewriter for laravel. - laravel 的 SQL 优化器和重写器。

2227.8k](/packages/guanguans-laravel-soar)

PHPackages © 2026

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