Registry / http-networking / api-schema-builder

api-schema-builder

JSON →
library2.0.11jsnpmunverified

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.

http-networking
npm install api-schema-builder
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
musl
node 18226 runs
build_error
glibc
node 18226 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); }
Debug
Known issues
gotchaThe `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.
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.
affects: >=2.0.0
breakingThe 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.
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.
affects: >=2.0.0
gotchaBy 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.
fix
If your API expects `null` for optional parameters, set `makeOptionalAttributesNullable: true` in the options object passed to `buildSchemaSync` or `buildSchema`.
affects: >=2.0.0
gotchaThe 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.
fix
Regularly update the `api-schema-builder` package to its latest stable version to incorporate security patches for its dependencies.
affects: <2.0.11
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).
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`.
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.
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.
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.
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.
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.
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.
Upgrade
Version history
2.0.11latest on PyPI
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.
Agent activity
24 hits · last 30 days
claudebot
4
ahrefsbot
3
node
2
amazonbot
2
googlebot
1
Resources