paddlehq/openapi-validator

Validate Responses against an OpenApi v3 schema

1.0.2 2018-09-19 08:09 UTC

This package is not auto-updated.

Last update: 2020-09-19 08:04:43 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License Daily Downloads

This package takes an OpenApi 3 schema file, converts it to a JSON Schema (draft 4) so it can be used for validation.

This is the used to validate a response that implements the Psr\Http\Message\ResponseInterface. interface against a given response in the OpenApi schema.

Installation

Library

git clone https://github.com/PaddleHQ/openapi-validator.git

Composer

Install PHP Composer

composer require paddlehq/openapi-validator

Usage

use PaddleHq\OpenApiValidator\OpenApiValidatorFactory;

$validatorFactory = new OpenApiValidatorFactory();

$schemaFilePath = __DIR__.'/schema.json'; // See below for example contents of this file
$validator = $validatorFactory->v3Validator($schemaFilePath);

$response = new Psr7Response();
$pathName = '/check/health';
$method = 'GET';
$responseCode = 200;
$contentType = 'application/json';

$validator->validateResponse(
    $response,
    $pathName,
    $method,
    $responseCode,
    $contentType
);

Example OpenApi v3 Schema file

{
  "openapi": "3.0.0",
  "info": {
    "title": "Schema Test",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "http://example.com",
      "description": "Test Schema"
    }
  ],
  "paths": {
    "/check/health": {
      "get": {
        "tags": [
          "Checks"
        ],
        "summary": "Health Check.",
        "description": "Returns an OK",
        "operationId": "api.check.user",
        "responses": {
          "200": {
            "description": "Success response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/HealthCheck"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "HealthCheck": {
        "description": "Default response from API server to check health",
        "properties": {
          "health": {
            "description": "expect an OK response",
            "type": "string"
          }
        },
        "required": ["health"],
        "type": "object"
      }
    }
  }
}

$validator->validateResponse throws a PaddleHq\OpenApiValidator\Exception\InvalidResponseException when the response does not pass the validation.

Credits

This package largely relies on justinrainbow/json-schema.

The code that handles conversion from OpenApi V3 to Json Schema has been taken from hskrasek/openapi-schema-to-jsonschema