{"id":12806,"library":"api-contract-validator","title":"API Contract Validator for Assertion Libraries","description":"The `api-contract-validator` package provides a plugin for popular JavaScript assertion libraries like Chai, Should.js, and Jest, enabling validation of API response schemas against OpenAPI (Swagger) definitions. This tool facilitates contract testing by transforming an OpenAPI definition file (YAML or JSON) into a JSON schema, which is then used to validate incoming HTTP responses. The current stable version is 2.2.8, with releases appearing to be maintenance-focused, primarily consisting of dependency upgrades rather than new features or breaking changes. Key differentiators include its plug-and-play integration with existing testing frameworks, support for various HTTP client response formats (axios, superagent, supertest, request, light-my-request), comprehensive assertion failure messages, and the ability to generate coverage reports for API contracts. It supports OpenAPI 3.0 and can handle multiple definition files, making it suitable for larger, modular API landscapes.","status":"maintenance","version":"2.2.8","language":"javascript","source_language":"en","source_url":"https://github.com/PayU/api-contract-validator","tags":["javascript","chai","chai-plugin","should","plugin","api","openapi","swagger","response","typescript"],"install":[{"cmd":"npm install api-contract-validator","lang":"bash","label":"npm"},{"cmd":"yarn add api-contract-validator","lang":"bash","label":"yarn"},{"cmd":"pnpm add api-contract-validator","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency for transforming API definitions into JSON schemas for validation. This package is frequently updated as seen in recent release notes.","package":"api-schema-builder","optional":false},{"reason":"Peer dependency when using the `chaiPlugin` for assertion chaining. Not directly required for the package's core logic but essential for its primary use case.","package":"chai","optional":true},{"reason":"Peer dependency when using the `shouldPlugin` for assertion chaining. Similar to Chai, it's optional but critical for its intended integration.","package":"should","optional":true},{"reason":"Peer dependency when using the `jestPlugin` for custom matchers. Optional but necessary for Jest test environments.","package":"jest","optional":true}],"imports":[{"note":"While CommonJS `require` is shown in the README, modern Node.js and bundlers encourage ESM `import`. The package primarily exposes named exports for its plugins.","wrong":"const matchApiSchema = require('api-contract-validator').chaiPlugin;","symbol":"chaiPlugin","correct":"import { chaiPlugin } from 'api-contract-validator';"},{"note":"For Should.js integration, the `shouldPlugin` is exported as a named export. Ensure you import it correctly for ESM or destructure it from `require` for CJS.","wrong":"const matchApiSchema = require('api-contract-validator').shouldPlugin;","symbol":"shouldPlugin","correct":"import { shouldPlugin } from 'api-contract-validator';"},{"note":"The `jestPlugin` registers custom matchers like `toMatchApiSchema` and `toHaveStatus`. It's crucial to call this imported function with your API definition path.","wrong":"const matchApiSchema = require('api-contract-validator').jestPlugin;","symbol":"jestPlugin","correct":"import { jestPlugin } from 'api-contract-validator';"},{"note":"While less common for direct use, the underlying `ApiContractValidator` class can be imported if you need to instantiate the validator directly without framework-specific plugins.","symbol":"ApiContractValidator","correct":"import { ApiContractValidator } from 'api-contract-validator';"}],"quickstart":{"code":"import { chaiPlugin } from 'api-contract-validator';\nimport path from 'path';\nimport { expect, use } from 'chai';\nimport supertest from 'supertest';\n\n// Assuming a simple Express app for demonstration\nconst express = require('express');\nconst app = express();\n\napp.get('/pet/:id', (req, res) => {\n  const id = parseInt(req.params.id, 10);\n  if (id === 123) {\n    res.status(200).json({ id: 123, name: 'Fido', species: 'Dog' });\n  } else {\n    res.status(404).json({ message: 'Pet not found' });\n  }\n});\n\n// API definitions path (assuming myApp.yaml exists relative to this file)\nconst apiDefinitionsPath = path.join(__dirname, 'myApp.yaml');\n\n// add as chai plugin\nuse(chaiPlugin({ apiDefinitionsPath }));\n\nconst request = supertest(app);\n\ndescribe('Pet API Contract', () => {\n  it('GET /pet/123 should match API schema', async () => {\n    // A dummy myApp.yaml for the quickstart\n    // paths:\n    //   /pet/{id}:\n    //     get:\n    //       parameters:\n    //         - in: path\n    //           name: id\n    //           schema:\n    //             type: integer\n    //           required: true\n    //       responses:\n    //         '200':\n    //           description: Successful response\n    //           content:\n    //             application/json:\n    //               schema:\n    //                 type: object\n    //                 properties:\n    //                   id:\n    //                     type: integer\n    //                   name:\n    //                     type: string\n    //                   species:\n    //                     type: string\n    //                 required:\n    //                   - id\n    //                   - name\n    //                   - species\n    const response = await request.get('/pet/123');\n    expect(response).to.have.status(200).and.to.matchApiSchema();\n  });\n\n  it('GET /pet/456 should not match API schema (e.g., 404 response)', async () => {\n    const response = await request.get('/pet/456');\n    expect(response).to.have.status(404);\n    // The validator would still check if the 404 response schema exists\n    // but in this quickstart, we're just checking the status.\n    // expect(response).to.matchApiSchema();\n  });\n});\n","lang":"typescript","description":"This quickstart demonstrates how to integrate `api-contract-validator` with Chai and Supertest to validate an Express.js API's responses against an OpenAPI specification. It sets up a basic server, defines an OpenAPI schema (conceptually, for a `/pet/{id}` endpoint), and then uses the `matchApiSchema` assertion to verify that a successful API response conforms to the defined contract. It illustrates both the setup and a basic test case for a GET request."},"warnings":[{"fix":"Use an OpenAPI linter or validator tool (e.g., `spectral`, `swagger-parser`) to pre-validate your API definition files before running tests with `api-contract-validator`.","message":"The package relies on an external OpenAPI/Swagger definition file. Errors in the definition file (e.g., invalid YAML/JSON, incorrect paths/methods) will lead to validation failures or unexpected behavior during test execution, but these errors stem from the definition, not the validator itself. Ensure your API definition is valid and accurate.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the `README` for an example of manually passing the response object. Ensure the `path`, `method`, `status`, `body`, and `headers` fields accurately reflect the API call and its response.","message":"This library is designed to work with specific HTTP response object structures from libraries like `axios`, `superagent`, `supertest`, and `request`. If you are using a custom HTTP client or a different library, you might need to manually construct an object with `path`, `method`, `status`, `body`, and `headers` properties to pass to `matchApiSchema`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Regularly update `api-contract-validator` to benefit from the latest `api-schema-builder` fixes and improvements. Thoroughly test your contract validations after significant dependency bumps.","message":"The `api-contract-validator` package uses `api-schema-builder` internally. Frequent updates to `api-schema-builder` (as seen in recent `api-contract-validator` patch releases) suggest ongoing maintenance and potential internal changes that could subtly affect schema interpretation, although typically without breaking the public API.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Verify that your `apiDefinitionsPath` correctly points to your OpenAPI/Swagger file and that the file includes the definition for `GET /api/v1/resource` with a `200` response schema. Check for typos in path or method.","cause":"The API definition file provided to the validator does not contain an entry for the specified path, method, and status code combination.","error":"Error: definition not found for path: /api/v1/resource, method: get, status: 200"},{"fix":"Examine the detailed assertion failure message (usually provided by Chai/Jest). Compare the actual response structure and data types against your OpenAPI definition's `schema` for the relevant response. This often indicates a mismatch between API implementation and its documentation.","cause":"The actual API response body or headers do not conform to the JSON schema generated from your OpenAPI definition for the given endpoint and status code.","error":"AssertionError: expected { Object (status, body, ...) } to match API schema"},{"fix":"Review the specified line and column in your YAML definition file. Use a YAML linter or editor with YAML validation to correct indentation and syntax errors.","cause":"The OpenAPI definition file (if YAML) has a syntax error, specifically incorrect indentation or formatting, preventing `api-schema-builder` from parsing it.","error":"YAMLException: YAMLException: bad indentation of a mapping entry at line X, column Y"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null}