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.
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
apiSchemaBuilder
✓ const apiSchemaBuilder = require('api-schema-builder');
✗ import apiSchemaBuilder from 'api-schema-builder';
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.
buildSchemaSync
✓ const { buildSchemaSync } = require('api-schema-builder');
✗ import { buildSchemaSync } from 'api-schema-builder';
While `buildSchemaSync` is a named export, the package's primary usage examples demonstrate CommonJS `require`.
buildSchema
✓ const { buildSchema } = require('api-schema-builder');
✗ import { buildSchema } from 'api-schema-builder';
This is the asynchronous version of the schema builder. Use `await` when calling it. The same CJS import pattern applies.
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.
const apiSchemaBuilder = require('api-schema-builder');
const path = require('path');
const fs = require('fs');
// Create a dummy OpenAPI/Swagger file content
const swaggerSpec = {
openapi: '3.0.0',
info: { title: 'Test API', version: '1.0.0' },
paths: {
'/items': {
post: {
summary: 'Create a new item',
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['name', 'price'],
properties: {
name: { type: 'string', minLength: 3 },
price: { type: 'number', minimum: 0 }
}
}
}
}
},
responses: {
'201': { description: 'Item created' },
'400': { description: 'Invalid input' }
}
}
}
}
};
const specPath = path.join(__dirname, 'swagger.json');
fs.writeFileSync(specPath, JSON.stringify(swaggerSpec, null, 2));
try {
const schema = apiSchemaBuilder.buildSchemaSync(specPath);
// Access the validator for a specific endpoint
const validateItemBody = schema['/items'].post.body.validate;
// Test valid data
const validData = { name: 'New Item', price: 10.5 };
const isValid = validateItemBody(validData);
console.log('Valid data check:', isValid); // Should be true
if (!isValid) {
console.error('Validation errors for valid data:', validateItemBody.errors);
}
// Test invalid data
const invalidData = { name: 'ab', price: -5 }; // name too short, price negative
const isInvalid = validateItemBody(invalidData);
console.log('Invalid data check:', isInvalid); // Should be false
if (!isInvalid) {
console.error('Validation errors for invalid data:', JSON.stringify(validateItemBody.errors, null, 2));
}
} catch (error) {
console.error('Error building schema:', error);
} finally {
// Clean up the dummy file
fs.unlinkSync(specPath);
}
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'validate')
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).
fixVerify 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`.
ENOENT: no such file or directory, open 'path/to/swagger.json'
The `buildSchemaSync` or `buildSchema` method was called with a path to an OpenAPI definition file that does not exist or is inaccessible.
fixEnsure 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.
Error: Can't resolve reference #/components/schemas/MySchema from id #
The OpenAPI definition contains a `$ref` (reference) to a schema or component that is either misspelled, missing, or improperly defined within the document.
fixInspect 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.
Validation Error: data should have required property 'propertyName'
The provided data for validation is missing a property that is marked as `required` in the corresponding OpenAPI schema.
fixExamine 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.
Audit
Dependencies
ajvrequiredCore validation engine used to compile OpenAPI schemas into executable validators.
decimal.jsrequiredUsed for handling high-precision decimal numbers, frequently updated in patch releases.