{"library":"openapi-validator-middleware","title":"OpenAPI Validator Middleware","description":"This package, `openapi-validator-middleware`, provides robust input validation for HTTP requests within Node.js frameworks such as Express, Koa, and Fastify. It leverages your existing OpenAPI (formerly Swagger) 2.0 or 3.0 definition files to automatically validate request bodies, headers, path parameters, and query parameters, using the powerful AJV library under the hood. The current stable version is 3.2.6, with the last significant update in February 2022. This suggests a maintenance-focused release cadence rather than active feature development, as over four years have passed since its last update. A key differentiator is its multi-framework support and its reliance on standardized OpenAPI definitions for validation logic, offering a consistent approach to API input schema enforcement. It was notably renamed from `express-ajv-swagger-validation` starting with version 2.0.0, which was a breaking change primarily affecting package naming and import paths for existing users.","language":"javascript","status":"maintenance","last_verified":"Wed Apr 22","install":{"commands":["npm install openapi-validator-middleware"],"cli":null},"imports":["import validator from 'openapi-validator-middleware';","const validator = require('openapi-validator-middleware');","import validator from 'openapi-validator-middleware'; const { InputValidationError } = validator;"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import express from 'express';\nimport path from 'path';\nimport validator from 'openapi-validator-middleware';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\n// Dummy OpenAPI spec for demonstration\nconst swaggerSpecPath = path.resolve('./swagger.yaml');\n// In a real app, this would be a real file:\n// fs.writeFileSync(swaggerSpecPath, `\n// openapi: 3.0.0\n// info:\n//   title: Test API\n//   version: 1.0.0\n// paths:\n//   /users:\n//     post:\n//       requestBody:\n//         required: true\n//         content:\n//           application/json:\n//             schema:\n//               type: object\n//               properties:\n//                 name:\n//                   type: string\n//                 email:\n//                   type: string\n//                   format: email\n//               required:\n//                 - name\n//                 - email\n//       responses:\n//         '200':\n//           description: User created\n// `);\n\n// In a real application, ensure the OpenAPI file exists.\n// For this example, we'll initialize without reading a file directly\n// to focus on the middleware usage, but you'd normally point to your spec.\n// For simplicity, we'll manually define a schema here.\n// In a real scenario, you would initialize with a path to your spec file:\n// validator.init(swaggerSpecPath, { source: 'fs' });\n\n// Simulate initialization with an in-memory spec if no file is present\n// For a real setup, provide a path to your YAML/JSON OpenAPI spec.\nconst inMemorySpec = {\n  openapi: '3.0.0',\n  info: { title: 'Test API', version: '1.0.0' },\n  paths: {\n    '/users': {\n      post: {\n        requestBody: {\n          required: true,\n          content: {\n            'application/json': {\n              schema: {\n                type: 'object',\n                properties: {\n                  name: { type: 'string' },\n                  email: { type: 'string', format: 'email' }\n                },\n                required: ['name', 'email']\n              }\n            }\n          }\n        },\n        responses: { '200': { description: 'User created' } }\n      }\n    }\n  }\n};\n\n// NOTE: In a real scenario, you'd call validator.init(pathToSwaggerFile)\n// We simulate by directly setting the internal schema for demonstration.\n// This part is for demonstration only, the library expects a file path.\nconsole.warn('Initializing openapi-validator-middleware without a physical file for demo. Provide a path to your spec in a real app.');\n// A more realistic init would be:\n// try {\n//   await validator.initAsync(swaggerSpecPath);\n// } catch (error) {\n//   console.error('Failed to initialize validator:', error.message);\n//   process.exit(1);\n// }\n\n// This requires manually mocking the internal state, not directly possible via public API.\n// So, for a runnable quickstart, we need an actual OpenAPI file.\n// Let's create a minimal one for the example.\n\nconst fs = require('fs');\nconst swaggerContent = `\nopenapi: 3.0.0\ninfo:\n  title: Test API\n  version: 1.0.0\npaths:\n  /users:\n    post:\n      summary: Create a new user\n      requestBody:\n        required: true\n        content:\n          application/json:\n            schema:\n              type: object\n              properties:\n                name:\n                  type: string\n                  minLength: 3\n                email:\n                  type: string\n                  format: email\n              required:\n                - name\n                - email\n      responses:\n        '201':\n          description: User created successfully\n        '400':\n          description: Invalid input\n`;\nfs.writeFileSync(swaggerSpecPath, swaggerContent);\n\nvalidator.init(swaggerSpecPath);\n\napp.use(express.json()); // Body parser middleware\n\napp.post('/users', validator.validate(), (req, res) => {\n  // If validation passes, process the request\n  res.status(201).json({ message: 'User created', data: req.body });\n});\n\n// Error handling middleware for validation errors\napp.use((err, req, res, next) => {\n  if (err instanceof validator.InputValidationError) {\n    return res.status(400).json({ \n      message: 'Validation Error', \n      errors: err.errors,\n      validationContext: err.validationContext \n    });\n  }\n  next(err);\n});\n\napp.listen(PORT, () => {\n  console.log(`Server running on http://localhost:${PORT}`);\n  console.log(`Test with: curl -X POST -H \"Content-Type: application/json\" -d '{\"name\": \"John Doe\", \"email\": \"john@example.com\"}' http://localhost:${PORT}/users`);\n  console.log(`Test validation failure with: curl -X POST -H \"Content-Type: application/json\" -d '{\"name\": \"Jo\", \"email\": \"invalid-email\"}' http://localhost:${PORT}/users`);\n});","lang":"typescript","description":"This quickstart demonstrates how to set up `openapi-validator-middleware` with an Express application. It initializes the validator with a dummy OpenAPI 3.0 specification file, applies the `validator.validate()` middleware to a route, and includes basic error handling for `InputValidationError`.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}