OpenAPI Validator
This provides Express middleware to validate routes based on an OpenAPI spec
Installation
- Make sure you have a
.npmrc
file with the proper auth token npm install @brightcove/openapi-validator
Pre-parsing YAML files
If you pass in a path to a YAML file, the library will parse it on initialization into JSON. For particularly large YAML files, this can lead to slow startup times, so the library offers the ability to pre-parse YAML files.
npx @brightcove/openapi-validator parse
Command List
help help
parse parses all YAML files in the specified folder into JSON
Options
-i, --import Folder path to read YAML files from (default: "api")
-e, --export Folder path to export JSON files to (default: "api")
Initialization
The library needs to be initialized with the path to a valid YAML and/or JSON file.
const path = require('path');
const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const yamlPath = path.join(__dirname, '../../api/index.yaml');
const jsonPath = path.join(__dirname, '../../api/index.json');
const app = express();
OpenAPIValidator.add("my api", yamlPath, jsonPath);
app.use(OpenAPIValidator.init());
const { validator, validateRequest, addResponseValidation, docs, schema } = OpenAPIValidator.api("my api");
Note: If there is only a single API added, calling OpenAPIValidator.api()
without a name will retrieve it.
Options
The following fields can be set when calling OpenAPIValidator.add()
Field | Type | Description | Required |
---|
name | String | Name used to retrieve the API | yes |
yamlPath | String | Path to the OpenAPI YAML file | yes, to view docs, or jsonPath must be included |
jsonPath | String | Path to the OpenAPI JSON file | yes, or yamlPath must be included |
host | String | The server host. This is used for the documentation middleware if static assets are behind a CDN | no |
emptyRequestValid | Boolean | Determines whether empty request bodies, for requests with required: true and no required properties, are considered valid. By default this is true . | no |
errorCodes | Object | Allows overriding of the default error code values | no |
errorCodes.InputValidationError | String | Overrides the InputValidationError code. By default it is "400.00" . | no |
errorCodes.OutputValidationError | String | Overrides the OutputValidationError code. By default it is "500.00" . | no |
docsPageTitle | String | The desired page title for the documentation route page. Otherwise the title will be "{name} Reference" | no |
Validate Requests
Manual
const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { validator } = OpenAPIValidator.api("my api");
router.post('/my/test/route', (req, res) => {
const { valid, errors } = validator.validateRequest(req);
});
Middleware
The validateRequest
middleware needs to be added to the specific route that needs validation before the route handler. If the middleware isn't added to the specific route, it will not function properly.
Any errors will be forwarded to the configured error handler as an InputValidationError
object.
const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { validateRequest } = OpenAPIValidator.api("my api");
router.post('/my/test/route', validateRequest, (req, res) => { ... });
router.use((err, req, res, next) => {
// err will be an `InputValidationError`
});
Validate Responses
Manual
const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { validator } = OpenAPIValidator.api("my api");
router.post('/my/test/route', (req, res) => {
const { valid, errors } = validator.validateResponse(req, statusCode, contentType, body);
});
Middleware
Automatic validation requires the middleware addResponseValidation
which adds the validate()
function to the res
object. If the middleware isn't added to the specific route, it will not function properly.
This function will validate the response and will prevent data from being returned to the client if it fails.
Any errors will be forwarded to the configured error handler as an OutputValidationError
object.
const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { addResponseValidation } = OpenAPIValidator.api("my api");
router.post('/my/test/route', addResponseValidation, (req, res) => {
...
const body = { "status": "success" };
res.validate().status(200).send(body);
});
router.use((err, req, res, next) => {
// err will be an `OutputValidationError`
});
Caveats
anyOf
and oneOf
aren't properly validated, so it's suggested to avoid these and have the logic for validation elsewhere- Nested schema refs will allow additional properties unless explicitely given
additionalProperties: false
- Deeply nested schema in arrays don't seem to be properly validated
JSON Schema
To view the JSON schema representation of the YAML file, you can use the following middleware
const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { schemaRoute } = OpenAPIValidator.api("my api");
app.use('/schema', schemaRoute());
Documentation
To view a Swagger UI render of the OpenAPI spec, you can use the following middleware
const { OpenAPIValidator } = require('@brightcove/openapi-validator');
const { docsRoute } = OpenAPIValidator.api("my api");
app.use('/docs', docsRoute());