{"id":27148792,"url":"https://github.com/payu/openapi-validator-middleware","last_synced_at":"2025-10-03T16:45:56.701Z","repository":{"id":38323277,"uuid":"107256133","full_name":"PayU/openapi-validator-middleware","owner":"PayU","description":"Input validation using Swagger (Open API) and ajv","archived":false,"fork":false,"pushed_at":"2023-06-02T20:29:44.000Z","size":1059,"stargazers_count":145,"open_issues_count":31,"forks_count":50,"subscribers_count":31,"default_branch":"master","last_synced_at":"2025-04-07T13:40:32.256Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PayU.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2017-10-17T10:56:52.000Z","updated_at":"2025-03-17T04:01:24.000Z","dependencies_parsed_at":"2023-11-27T00:11:36.111Z","dependency_job_id":"3d87a60b-4ed6-4a9c-b522-ab6bc09661b1","html_url":"https://github.com/PayU/openapi-validator-middleware","commit_stats":{"total_commits":179,"total_committers":39,"mean_commits":4.589743589743589,"dds":0.7877094972067039,"last_synced_commit":"1effab3130e3ea72414f475d459a10a096d13b19"},"previous_names":["zooz/express-ajv-swagger-validation"],"tags_count":54,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PayU%2Fopenapi-validator-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PayU%2Fopenapi-validator-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PayU%2Fopenapi-validator-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PayU%2Fopenapi-validator-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PayU","download_url":"https://codeload.github.com/PayU/openapi-validator-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247839723,"owners_count":21004800,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-08T12:24:30.985Z","updated_at":"2025-10-03T16:45:51.657Z","avatar_url":"https://github.com/PayU.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# openapi-validator-middleware\n\n[![NPM Version][npm-image]][npm-url]\n![main workflow](https://github.com/PayU/openapi-validator-middleware/actions/workflows/main.yml/badge.svg)\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n[![Known Vulnerabilities][snyk-image]][snyk-url]\n[![Apache 2.0 License][license-image]][license-url]\n\nThis package provides data validation within an Express, Koa or Fastify app according to a [Swagger/OpenAPI definition](https://swagger.io/specification/). It uses [Ajv](https://www.npmjs.com/package/ajv) under the hood for validation.\n\nNOTICE: As this package gone through a long way, as we added support for OpenAPI definitions, while also adding support for more frameworks such as Koa and Fastify, we finally took the step of changing [express-ajv-swagger-validation](https://www.npmjs.com/package/express-ajv-swagger-validation) name to something that describes it better. As of now we'll be using the name [openapi-validator-middleware](https://www.npmjs.com/package/openapi-validator-middleware) instead.  \nThere are no code changes in `openapi-validator-middleware@2.0.0` compared to `express-ajv-swagger-validation@1.2.0` apart from the name change.\n\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n**Table of Contents**  \u003c!-- *generated with [DocToc](https://github.com/thlorenz/doctoc)* --\u003e\n\n- [openapi-validator-middleware](#openapi-validator-middleware)\n  - [Installation](#installation)\n  - [API](#api)\n    - [openapi-validator-middleware.validate(fastifyOptions)](#openapi-validator-middlewarevalidatefastifyoptions)\n      - [fastifyOptions](#fastifyoptions)\n    - [openapi-validator-middleware.init(pathToSwaggerFile, options)](#openapi-validator-middlewareinitpathtoswaggerfile-options)\n    - [openapi-validator-middleware.initAsync(pathToSwaggerFile, options)](#openapi-validator-middlewareinitasyncpathtoswaggerfile-options)\n      - [Options](#options)\n  - [Usage Example](#usage-example)\n    - [Express](#express)\n    - [Koa](#koa)\n    - [Fastify](#fastify)\n    - [Multiple-instances](#multiple-instances)\n  - [Important Notes](#important-notes)\n    - [Schema Objects](#schema-objects)\n    - [Multipart/form-data (files)](#multipartform-data-files)\n    - [Fastify support](#fastify-support)\n    - [Koa support](#koa-support)\n    - [Koa packages](#koa-packages)\n  - [Known Issues with OpenAPI 3](#known-issues-with-openapi-3)\n  - [Running Tests](#running-tests)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n## Installation\n\nInstall using the node package registry:\n\n```bash\nnpm install --save openapi-validator-middleware\n```\n\nThen import the module in your code:\n\n```js\nconst swaggerValidation = require('openapi-validator-middleware');\n```\n\n## API\n\n### openapi-validator-middleware.validate(fastifyOptions)\n\nThis middleware function validates the request body, headers, path parameters and query parameters according to the _paths_ definition of the swagger file. Make sure to use this middleware inside a route definition in order to have `req.route.path` assigned to the most accurate express route.\n\n- `fastifyOptions`: Only applicable for `fastify` framework. See below.\n\n#### fastifyOptions\n\n- `skiplist`: Endpoint paths for which validation should not be applied. An array of strings in RegExp format, e. g. `['^/pets$']` \n\n### openapi-validator-middleware.init(pathToSwaggerFile, options)\n\nInitialize the middleware using a swagger definition.\nThe function executes synchronously and does not return anything.\n\n- `pathToSwaggerFile`: Path to the swagger definition.\n- `options`: Additional options for the middleware ([see below](#options)).\n\n### openapi-validator-middleware.initAsync(pathToSwaggerFile, options)\n\nInitialize the middleware using a swagger definition.\nThe function executes asynchronously and the resolved promise does not return anything.\n\nThis Initilaztion function also supports schema with references to external files. \n\n- `pathToSwaggerFile`: Path to the swagger definition.\n- `options`: Additional options for the middleware ([see below](#options)).\n\n#### Options\n\nOptions currently supported:\n- `framework` - Defines in which framework the middleware is working ('fastify', 'koa' or 'express'). As default, set to 'express'.\n- `formats` - Array of formats that can be added to `ajv` configuration, each element in the array should include `name` and `pattern`.\n    ```js\n    formats: [\n        { name: 'double', pattern: /\\d+\\.(\\d+)+/ },\n        { name: 'int64', pattern: /^\\d{1,19}$/ },\n        { name: 'int32', pattern: /^\\d{1,10}$/ }\n    ]\n    ```\n\n- `keywords` - Array of keywords that can be added to `ajv` configuration, each element in the array can be either an object or a function. \nIf the element is an object, it must include `name` and `definition`. If the element is a function, it should accept `ajv` as its first argument and inside the function you need to call `ajv.addKeyword` to add your custom keyword \n- `beautifyErrors`- Boolean that indicates if to beautify the errors, in this case it will create a string from the Ajv error.\n    - Examples:\n        - `query/limit should be \u003c= 100` - query param\n        - `path/petId should NOT be shorter than 3 characters` - path param not in format\n        - `body/[0].test.field1 should be string` - Item in an array body\n        - `body/test should have required property 'field1'` - nested field\n        - `body should have required property 'name'` - Missing field in body\n\n    You can see more examples in the [tests](./test).\n\n- `firstError` - Boolean that indicates if to return only the first error.\n- `makeOptionalAttributesNullable` - Boolean that forces preprocessing of Swagger schema to include 'null' as possible type for all non-required properties. Main use-case for this is to ensure correct handling of null values when Ajv type coercion is enabled\n- `ajvConfigBody` - Object that will be passed as config to new Ajv instance which will be used for validating request body. Can be useful to e. g. enable type coercion (to automatically convert strings to numbers etc). See Ajv documentation for supported values.\n- `ajvConfigParams` - Object that will be passed as config to new Ajv instance which will be used for validating request body. See Ajv documentation for supported values.\n- `contentTypeValidation` - Boolean that indicates if to perform content type validation in case `consume` field is specified and the request body is not empty.\n- `expectFormFieldsInBody` - Boolean that indicates whether form fields of non-file type that are specified in the schema should be validated against request body (e. g. Multer is copying text form fields to body)\n- `errorFormatter` - optional custom function that will be invoked to create a validation error that will be thrown if Ajv validation fails. Function should accept two parameters: `(errors, middlewareOptions)` and return an error that will be thrown.\n\n## Usage Example\n### Express\n```js\nswaggerValidation.init('test/unit-tests/input-validation/pet-store-swagger.yaml');\nconst app = express();\napp.use(bodyParser.json());\napp.get('/pets', swaggerValidation.validate, (req, res, next) =\u003e {\n    return res.json({ result: 'OK' });\n});\napp.post('/pets', swaggerValidation.validate, (req, res, next) =\u003e {\n    return res.json({ result: 'OK' });\n});\napp.get('/pets/:petId', swaggerValidation.validate, (req, res, next) =\u003e {\n    return res.json({ result: 'OK' });\n});\n\napp.use((err, req, res, next) =\u003e {\n    if (err instanceof swaggerValidation.InputValidationError) {\n        return res.status(400).json({ more_info: JSON.stringify(err.errors) });\n    }\n});\n\nconst server = app.listen(serverPort, () =\u003e {});\n```\n\n### Koa\n```js\n'use strict';\nconst Koa = require('koa');\nconst Router = require('koa-router');\nconst bodyParser = require('koa-bodyparser');\nconst inputValidation = require('openapi-validator-middleware');\nconst app = new Koa();\nconst router = new Router();\napp.use(bodyParser());\napp.use(router.routes());\ninputValidation.init('test/pet-store-swagger.yaml', { framework: 'koa' });\n\nrouter.get('/pets', inputValidation.validate, async (ctx, next) =\u003e {\n    ctx.status = 200;\n    ctx.body = { result: 'OK' };\n});\nrouter.post('/pets', inputValidation.validate, async (ctx, next) =\u003e {\n    ctx.status = 200;\n    ctx.body = { result: 'OK' };\n});\nrouter.get('/pets/:petId', inputValidation.validate, async (ctx, next) =\u003e {\n    ctx.status = 200;\n    ctx.body = { result: 'OK' };\n});\nrouter.put('/pets', inputValidation.validate, async (ctx, next) =\u003e {\n    ctx.status = 200;\n    ctx.body = { result: 'OK' };\n});\n\napp.use(async (ctx, next) =\u003e {\n    try {\n        return await next();\n    } catch (err) {\n        if (err instanceof inputValidation.InputValidationError) {\n            ctx.status = 400;\n            ctx.body = err.errors;\n        }\n        throw err;\n    }\n})\napp.listen(process.env.PORT || 8888, function () {\n    console.log('listening on', this.address());\n});\n```\n\n### Fastify\n```js\n'use strict';\nconst fastify = require('fastify');\nconst inputValidation = require('openapi-validator-middleware');\n\nasync function getApp() {\n    inputValidation.init('test/pet-store-swagger.yaml', { \n        framework: 'fastify'\n    });\n    const app = fastify({ logger: true });\n\n    app.register(inputValidation.validate({\n      skiplist: ['^/_metrics$']\n    }));\n    app.setErrorHandler(async (err, req, reply) =\u003e {\n        if (err instanceof inputValidation.InputValidationError) {\n             return reply.status(400).send({ more_info: JSON.stringify(err.errors) });\n        }\n\n        reply.status(500);\n        reply.send();\n    });\n\n    app.get('/pets', (req, reply) =\u003e {\n        reply.status(204).send();\n    });\n\n    await app.ready();\n    return app;\n}\n```\n\n### multiple-instances\n```js\nconst inputValidation = require('openapi-validator-middleware');\nconst validatorA = inputValidation.getNewMiddleware('test/pet-store-swaggerA.yaml', {framework: 'express'});\nconst validatorB = inputValidation.getNewMiddleware('test/pet-store-swaggerB.yaml', {framework: 'express'});\n\napp.get('/pets', validatorA.validate, (req, res, next) =\u003e {\n    return res.json({ result: 'OK' });\n});\n\napp.post('/pets', validatorB.validate, (req, res, next) =\u003e {\n    return res.json({ result: 'OK' });\n});\n\n```\n## Important Notes\n\n### Schema Objects\n\nIt is important to set the `type` property of any [Schema Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schema-object) explicitly to `object`. Although it isn't required in the OpenAPI specification, it is necessary in order for [Ajv](https://www.npmjs.com/package/ajv) to work correctly.\n\n### Multipart/form-data (files) \n\nMultipart/form-data (files) support is based on [`express/multer`](https://github.com/expressjs/multer).\n\n### Fastify support\n\nFastify support requires `uri-js` dependency to be installed. Make sure to run `npm install uri-js`.\nWhen using this package as a middleware for fastify, the validations errors will be thrown.\n\n### Koa support\n\nWhen using this package as middleware for koa, the validations errors will be thrown.\n\n### Koa packages\n\nThis package supports Koa servers that use [`koa-router`](https://www.npmjs.com/package/koa-router), [`koa-bodyparser`](https://www.npmjs.com/package/koa-bodyparser) and [`koa-multer`](https://www.npmjs.com/package/koa-multer).\n\n## Known Issues with OpenAPI 3 \n\n- Inheritance with a discriminator is supported only if the ancestor object is the discriminator.\n- The discriminator support in the inheritance chain stops when getting to a child without a discriminator (a leaf in the inheritance tree), meaning a child without a discriminator cannot point to another child with a discriminator.\n\n## Running Tests\n\nThe tests use mocha, istanbul and mochawesome. Run them using the node test script:\n\n```bash\nnpm test\n```\n\n[npm-image]: https://img.shields.io/npm/v/openapi-validator-middleware.svg?style=flat\n[npm-url]: https://npmjs.org/package/openapi-validator-middleware\n[coveralls-image]: https://coveralls.io/repos/github/PayU/openapi-validator-middleware/badge.svg?branch=master\n[coveralls-url]: https://coveralls.io/github/PayU/openapi-validator-middleware?branch=master\n[downloads-image]: http://img.shields.io/npm/dm/openapi-validator-middleware.svg?style=flat\n[downloads-url]: https://img.shields.io/npm/dm/openapi-validator-middleware.svg\n[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat\n[license-url]: LICENSE\n[snyk-image]: https://snyk.io/test/github/PayU/openapi-validator-middleware/badge.svg?targetFile=package.json\n[snyk-url]: https://snyk.io/test/github/PayU/openapi-validator-middleware?targetFile=package.json\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpayu%2Fopenapi-validator-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpayu%2Fopenapi-validator-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpayu%2Fopenapi-validator-middleware/lists"}