{"id":12809,"library":"api-schema-builder","title":"OpenAPI API Schema Builder","description":"The `api-schema-builder` package facilitates the generation of input and response validators directly from OpenAPI (formerly Swagger) specifications. It integrates with `ajv` (Another JSON Schema Validator) to compile these definitions into executable validation functions for various parts of an HTTP request and response, including path parameters, query strings, headers, and request/response bodies. The current stable version is 2.0.11, with the last release in January 2022. The project's release cadence is infrequent, suggesting a maintenance-focused phase. A key differentiator is its ability to seamlessly integrate existing OpenAPI definitions, automating the enforcement of schema compliance without requiring manual AJV schema composition. It supports OpenAPI 3.0 content type validation and offers customization options for AJV configuration, alongside specific handling for nullable attributes.","status":"maintenance","version":"2.0.11","language":"javascript","source_language":"en","source_url":"https://github.com/PayU/api-schema-builder","tags":["javascript","ajv","swagger","OpenAPI","open api","validation","validator"],"install":[{"cmd":"npm install api-schema-builder","lang":"bash","label":"npm"},{"cmd":"yarn add api-schema-builder","lang":"bash","label":"yarn"},{"cmd":"pnpm add api-schema-builder","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core validation engine used to compile OpenAPI schemas into executable validators.","package":"ajv","optional":false},{"reason":"Used for handling high-precision decimal numbers, frequently updated in patch releases.","package":"decimal.js","optional":false}],"imports":[{"note":"The library primarily uses CommonJS `require` syntax. Direct ESM `import` is not officially documented and may not work as expected without a transpilation step or ESM wrapper.","wrong":"import apiSchemaBuilder from 'api-schema-builder';","symbol":"apiSchemaBuilder","correct":"const apiSchemaBuilder = require('api-schema-builder');"},{"note":"While `buildSchemaSync` is a named export, the package's primary usage examples demonstrate CommonJS `require`.","wrong":"import { buildSchemaSync } from 'api-schema-builder';","symbol":"buildSchemaSync","correct":"const { buildSchemaSync } = require('api-schema-builder');"},{"note":"This is the asynchronous version of the schema builder. Use `await` when calling it. The same CJS import pattern applies.","wrong":"import { buildSchema } from 'api-schema-builder';","symbol":"buildSchema","correct":"const { buildSchema } = require('api-schema-builder');"}],"quickstart":{"code":"const apiSchemaBuilder = require('api-schema-builder');\nconst path = require('path');\nconst fs = require('fs');\n\n// Create a dummy OpenAPI/Swagger file content\nconst swaggerSpec = {\n  openapi: '3.0.0',\n  info: { title: 'Test API', version: '1.0.0' },\n  paths: {\n    '/items': {\n      post: {\n        summary: 'Create a new item',\n        requestBody: {\n          required: true,\n          content: {\n            'application/json': {\n              schema: {\n                type: 'object',\n                required: ['name', 'price'],\n                properties: {\n                  name: { type: 'string', minLength: 3 },\n                  price: { type: 'number', minimum: 0 }\n                }\n              }\n            }\n          }\n        },\n        responses: {\n          '201': { description: 'Item created' },\n          '400': { description: 'Invalid input' }\n        }\n      }\n    }\n  }\n};\n\nconst specPath = path.join(__dirname, 'swagger.json');\nfs.writeFileSync(specPath, JSON.stringify(swaggerSpec, null, 2));\n\ntry {\n  const schema = apiSchemaBuilder.buildSchemaSync(specPath);\n\n  // Access the validator for a specific endpoint\n  const validateItemBody = schema['/items'].post.body.validate;\n\n  // Test valid data\n  const validData = { name: 'New Item', price: 10.5 };\n  const isValid = validateItemBody(validData);\n  console.log('Valid data check:', isValid); // Should be true\n  if (!isValid) {\n    console.error('Validation errors for valid data:', validateItemBody.errors);\n  }\n\n  // Test invalid data\n  const invalidData = { name: 'ab', price: -5 }; // name too short, price negative\n  const isInvalid = validateItemBody(invalidData);\n  console.log('Invalid data check:', isInvalid); // Should be false\n  if (!isInvalid) {\n    console.error('Validation errors for invalid data:', JSON.stringify(validateItemBody.errors, null, 2));\n  }\n} catch (error) {\n  console.error('Error building schema:', error);\n} finally {\n  // Clean up the dummy file\n  fs.unlinkSync(specPath);\n}","lang":"javascript","description":"This example demonstrates how to synchronously build a schema from an OpenAPI specification file and then use the generated `ajv` validators to validate request body data for a specific endpoint. It shows both successful and failed validation cases."},"warnings":[{"fix":"Ensure your project uses CommonJS `require()` statements, or configure your build system (e.g., Babel, Webpack) to transpile ES Modules to CommonJS if `import` syntax is desired.","message":"The `api-schema-builder` library is designed around CommonJS (`require`) module syntax. Attempting to use ES Modules (`import`) directly may lead to `TypeError: require is not a function` or incorrect import resolution, especially in modern Node.js environments without proper transpilation.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Review the 'Open API 3 - known issues' section in the README before relying on these advanced OpenAPI features. Consider workarounds or alternative validation methods for unsupported scenarios.","message":"The library explicitly lists 'Open API 3 - known issues' in its documentation, including limitations in supporting inheritance with discriminators, specific discriminator patterns, and restricted content types ('application/json' only) for response validators. It also notes that response validators do not support links and `writeOnly` attributes.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"If your API expects `null` for optional parameters, set `makeOptionalAttributesNullable: true` in the options object passed to `buildSchemaSync` or `buildSchema`.","message":"By default, `ajv` does not treat `null` as a valid value for optional properties unless explicitly specified. The `makeOptionalAttributesNullable` option (Boolean) forces preprocessing of the Swagger schema to include `null` as a possible type for all non-required properties. Failing to enable this option can cause validation errors when `null` is passed for optional fields.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Regularly update the `api-schema-builder` package to its latest stable version to incorporate security patches for its dependencies.","message":"The package has had multiple vulnerability fixes for its dependencies (e.g., `decimal.js`). While these are generally patched in minor releases, prolonged use of older versions without regular updates could expose applications to known security vulnerabilities.","severity":"gotcha","affected_versions":"<2.0.11"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify that the OpenAPI specification correctly defines the path, method, and the specific schema (e.g., `requestBody`, `parameters`) you are trying to validate against. Double-check the casing and existence of the definitions in your `swagger.json` or `openapi.yaml`.","cause":"Attempting to access a validator for a path, method, or schema component that does not exist in the loaded OpenAPI definition (e.g., trying to validate 'body' for a GET request without a defined request body schema).","error":"TypeError: Cannot read properties of undefined (reading 'validate')"},{"fix":"Ensure the provided `PathToSwaggerFile` argument is correct, absolute, and that the file exists and is readable by the Node.js process. Use `path.resolve()` for robustness.","cause":"The `buildSchemaSync` or `buildSchema` method was called with a path to an OpenAPI definition file that does not exist or is inaccessible.","error":"ENOENT: no such file or directory, open 'path/to/swagger.json'"},{"fix":"Inspect your OpenAPI specification for broken `$ref` pointers. Ensure that all referenced components (e.g., under `#/components/schemas/`) are correctly defined and that their names match the references exactly, including casing.","cause":"The OpenAPI definition contains a `$ref` (reference) to a schema or component that is either misspelled, missing, or improperly defined within the document.","error":"Error: Can't resolve reference #/components/schemas/MySchema from id #"},{"fix":"Examine the `errors` array returned by the `validate` function to identify which required properties are missing. Adjust the input data to include all mandatory fields as defined in your OpenAPI specification.","cause":"The provided data for validation is missing a property that is marked as `required` in the corresponding OpenAPI schema.","error":"Validation Error: data should have required property 'propertyName'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null}