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.
npm install api-schema-builderVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
If your API expects `null` for optional parameters, set `makeOptionalAttributesNullable: true` in the options object passed to `buildSchemaSync` or `buildSchema`.
Regularly update the `api-schema-builder` package to its latest stable version to incorporate security patches for its dependencies.
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`.
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.
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.
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.