Request and response validators based on the OpenAPI Specification.
- Validate any request and response with a pre-prepared OpenAPI Spec.
- Automatically load specs from Laravel OpenAPI or L5 Swagger.
- You can also load your own specs without using these libraries.
- You can customize validation and error logging behavior on a per-route or application-wide basis.
- Can display Swagger UI. You can view the documentation and test the API.
- PHP 8.1 or higher
- Laravel 9.0 or higher
You can install the package via composer:
composer require kentaroutakeda/laravel-openapi-validator
-
Configure OpenAPI Specification
If you're using Laravel OpenAPI, you don't need to do anything.
For L5 Swagger, the following settings are required:
# .env OPENAPI_VALIDATOR_PROVIDER="l5-swagger"
How to load your own schema without using these packages will be explained later.
-
Register Middleware
Route::get('/example', ExampleController::class) ->middleware(OpenApiValidator::class); // <- Add this line
Routes with this setting will be validated for all requests including Feature Tests, and depending on the settings, responses as well.
NOTE:
This repository's ./e2e directory contains working examples for e2e testing. You can see middleware configuration examples in Routing, and actual validations and failures in Tests. -
(Optional) Customize Middleware
If necessary, you can change Middleware behavior for each route.
Route::get('/', ExampleController::class) ->middleware(OpenApiValidator::config( provider: 'admin-api', // <- Use spec other than default skipResponseValidation: true // <- Skip Response Validation ));
NOTE:
Response validation for large amounts of data can take a long time. It would be a good idea to switch on/off validation depending on the route andAPP_*
environment variables. -
Deployment
When deploying your application to production, you should make sure that you run the
openapi-validator:cache
Artisan command during your deployment process:php artisan openapi-validator:cache
This command caches the OpenAPI Spec defined in your application. If you change the definition for development, you need to clear it as follows:
php artisan openapi-validator:clear
You can view the Swagger UI just by installing the package. No additional configuration is required.
-
Install package.
composer require --dev swagger-api/swagger-ui
-
Display
APP_URL/openapi-validator/documents
in browser.open http://localhost:8000/openapi-validator/documents
NOTE:
By default, the Swagger UI can only be displayed when APP_DEBUG
is enabled.
You can publish the config file to change behavior.
php artisan openapi-validator:publish
Alternatively, most settings can be changed using environment variables. Check the comments in config/openapi-validator.php for details.
-
If you want to use your own schema providers, first publish the config.
-
Next, implement a class to retrieve the schema.
class MyResolver implements ResolverInterface { public function getJson(array $options): string { // This example assumes that the schema exists in the root directory. return File::get(base_path('openapi.json')); } }
-
Finally, set it in your config.
return [ // Set the provider name. 'default' => 'my-resolver', 'providers' => [ // Set the provider name you created. 'my-resolver' => [ // Specify the class you created in the `resolver` parameter. 'resolver' => MyResolver::class, ], ], ];
By default, it is formatted according to RFC 7807 - Problem Details for HTTP APIs.
Validation errors, stack traces and original response can also be included depending on your settings. For example, it might look like this:
{
"title": "NoResponseCode",
"detail": "OpenAPI spec contains no such operation [/,get,201]", // Error reason
"status": 500, // Same as HTTP response code
"originalResponse": { "status": "201" }, // Original response before validation
"trace": [
{ "error": "...", "message": "...", "file": "...", "line": 42 },
{ "...": "..." }
]
}
Here's how to change to a different format:
-
First, implement a class to generate a response. For example:
class MyErrorRenderer implements ErrorRendererInterface { public function render( Request $request, \Throwable $error, ErrorType $errorType, ): Response { return new Response( match ($errorType) { ErrorType::Request => "Request Error: " . $error->getMessage(), ErrorType::Response => "Response Error: " . $error->getMessage(), } ); } }
-
Next, register the class to the service container.
// AppServiceProvider.php public function register(): void { $this->app->bind( ErrorRendererInterface::class, MyErrorRenderer::class ); }
If a validation error occurs, an event will be fired depending on the type of error.
ValidationFailedInterface
- All errorsRequestValidationFailed
- Request validation errorResponseValidationFailed
- Response validation error
Feel free to open an Issue or add a Pull request.
When adding a pull request, please refer to the following setup steps.
# Clone this repository and move to the directory.
git clone https://github.com/KentarouTakeda/laravel-openapi-validator.git
cd laravel-openapi-validator
# Install dependencies.
composer install
# (Optional) Install tools: The commit hook automatically formats the code.
npm install
# Run tests.
vendor/bin/phpunit
Laravel OpenAPI Validator is open-sourced software licensed under the MIT license.