Gathering detailed insights and metrics for response-schema-validator
Gathering detailed insights and metrics for response-schema-validator
Gathering detailed insights and metrics for response-schema-validator
Gathering detailed insights and metrics for response-schema-validator
openapi-response-validator
Validate a response according to an openapi schema.
@leoscope/openapi-response-validator
Validate a response according to an openapi schema.
joi-piece-validator
- Helps you validate part of the schema. - For middleware function will return the validation error inside the response
@restfulhead/ajv-openapi-request-response-validator
AJV based implementation to validate http requests and responses against an OpenAPI schema
npm install response-schema-validator
Typescript
Module System
Min. Node Version
Node Version
NPM Version
Cumulative downloads
Total Downloads
A Node.js library that validates HTTP response schemas against OpenAPI specifications. It integrates seamlessly with popular HTTP clients to ensure API responses conform to their documented schemas.
/users/{userId}
1npm install response-schema-validator 2# or 3yarn add response-schema-validator
1const validator = require("response-schema-validator"); 2 3// Create validator instance with OpenAPI specification 4const validatorInstance = validator("./openapi.json"); // or .yaml/.yml 5 6// Validate response data 7const responseData = [ 8 { id: 1, name: "John Doe", email: "john@example.com" }, 9 { id: 2, name: "Jane Smith", email: "jane@example.com" } 10]; 11 12const result = validatorInstance.validate( 13 responseData, 14 "/users", // API path 15 "GET", // HTTP method 16 200 // Status code 17); 18 19if (result.valid) { 20 console.log("✅ Response is valid!"); 21} else { 22 console.log("❌ Validation failed:"); 23 result.errors?.forEach(error => { 24 console.log(` ${error.path}: ${error.message}`); 25 }); 26}
The library supports automatic response validation for multiple HTTP clients:
1const validator = require("response-schema-validator"); 2const axios = require("axios"); 3 4const v = validator("./openapi.json"); 5 6// With Axios instance 7const instance = axios.create({ baseURL: "https://api.example.com" }); 8v.intercept(instance); 9instance.get("/users").then(res => console.log("Got", res.data.length, "users")); 10 11// With Axios static 12v.intercept(axios); 13axios.get("https://api.example.com/users/1").then(res => console.log("User:", res.data.name)); 14 15// Validation errors are thrown automatically 16axios.get("https://api.example.com/comments") 17 .catch(err => console.log("Validation error:", err.message));
1const validator = require("response-schema-validator"); 2const superagent = require("superagent"); 3 4const v = validator("./openapi.json"); 5const agent = superagent.agent(); 6v.intercept(agent); 7 8// All requests through this agent will be validated 9agent.get("https://api.example.com/users") 10 .then(res => console.log("Got", res.body.length, "users"));
1const validator = require("response-schema-validator"); 2 3const v = validator("./openapi.json"); 4 5// Only works with global fetch (not node-fetch) 6if (globalThis.fetch) { 7 const interceptedFetch = v.intercept(globalThis.fetch); 8 interceptedFetch("https://api.example.com/users") 9 .then(res => res.json()) 10 .then(data => console.log("Got", data.length, "users")); 11}
Note: Fetch interception only works with the global fetch
function. Third-party implementations like node-fetch
are not supported.
The library supports OpenAPI path parameters like /users/{userId}
:
1// OpenAPI spec defines: /users/{userId} 2// Actual request: /users/123 3 4const userResponse = { id: 123, name: "John Doe", email: "john@example.com" }; 5 6const result = validatorInstance.validate( 7 userResponse, 8 "/users/123", // Actual path with parameter value 9 "GET", 10 200 11);
The validate()
method returns a ValidationResult
object:
1interface ValidationResult { 2 valid: boolean; 3 response: unknown; // The response data that was validated 4 url: string; // The URL path 5 method: string; // HTTP method 6 statusCode: number; // HTTP status code 7 errors?: Array<{ 8 path: string; // JSON path where error occurred 9 message: string; // Error description 10 }>; 11}
Example error handling:
1const result = validatorInstance.validate(responseData, "/users", "GET", 200); 2 3if (!result.valid && result.errors) { 4 result.errors.forEach(error => { 5 console.log(`Error at ${error.path}: ${error.message}`); 6 }); 7}
You can customize how validation errors are handled:
1const validator = require("response-schema-validator"); 2 3// Define custom error behavior 4const customErrorBehavior = { 5 onValidationError(validationResult) { 6 console.error("Validation failed:", validationResult.errors); 7 // You can choose to throw, log, or handle errors differently 8 }, 9 onSchemaError(error) { 10 console.error("Schema error:", error); 11 } 12}; 13 14// Pass custom behavior when creating validator 15const v = validator("./openapi.json", customErrorBehavior);
1import validator from "response-schema-validator"; 2import type { ValidationResult } from "response-schema-validator"; 3 4const validatorInstance = validator("./openapi.json"); 5 6const result: ValidationResult = validatorInstance.validate( 7 responseData, 8 "/users", 9 "GET", 10 200 11);
validator(openapiFilePath: string, errorBehavior?: ErrorBehavior)
Creates a new validator instance.
ResponseSchemaValidator
instanceResponseSchemaValidator
validate(responseBody: any, url: string, method: string, statusCode: number): ValidationResult
Validates response data against the OpenAPI schema.
ValidationResult
objectintercept<T extends AcceptableClient>(client: T): T
Adds response validation interceptor to an HTTP client.
Supported client types:
AxiosInstance
- Created with axios.create()
AxiosStatic
- The default axios objectfetch
- The global fetch function (not node-fetch)SuperAgentAgent
- Created with superagent.agent()
Check out the example files in the examples/
directory:
examples/demo.js
- Basic validation examplesexamples/intercept-axios.js
- Axios interceptor examplesexamples/intercept-fetch.js
- Fetch API interceptor examplesexamples/intercept-superagent.js
- SuperAgent interceptor examplesexamples/using-typescript.ts
- TypeScript usage exampleexamples/test-api.json
- Sample OpenAPI specificationTo run the examples:
1# Build the project first 2npm run build 3 4# Run basic validation demo 5node examples/demo.js 6 7# Run HTTP client interceptor examples 8node examples/intercept-axios.js 9node examples/intercept-fetch.js 10node examples/intercept-superagent.js
When a response doesn't match the schema, you'll get a clear error message:
1// If your OpenAPI spec expects { id: number, text: string } 2// but the API returns { id: 1, name: "...", email: "...", body: "..." } 3 4// Error message: 5"Response validation failed for GET /comments (status 200): /0: must have required property 'text'"
1# Clone the repository 2git clone https://github.com/yourusername/response-schema-validator.git 3cd response-schema-validator 4 5# Install dependencies 6npm install
1npm run build
1npm test
1npm run lint
git checkout -b feature/amazing-feature
)npm test && npm run lint
)git commit -m 'Add some amazing feature'
)git push origin feature/amazing-feature
)MIT
fetch
function, not node-fetch
globalThis.fetch
is available in your environmentsuperagent.agent()
superagent
object directlyIf you encounter any issues or have questions, please open an issue on GitHub.
No vulnerabilities found.
No security vulnerabilities found.
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year