Generate standalone request validators from OpenAPI specs and validate incoming requests in serverless and lightweight Node.js runtimes.
Built on AJV, this package includes runtime helpers for AWS Lambda API Gateway events, lambda-api, and Express.
Install the package as a normal dependency, since it is required both at build time and runtime:
npm install openapi-request-validationGenerate validators from a spec into a target directory:
openapi-request-validation ./openapi.yaml ./src/generatedThis writes a file such as ./src/generated/openapi-validators.js. Each operation with a request shape gets an export
like validateCreateUserRequest. Your tsconfig must specify allowJs: true to use these validators.
Use validateApiGatewayEvent(...) to validate a raw API Gateway event before your handler logic runs.
import {validateCreateCustomerOrderRequest} from "./generated/openapi-validators.js"
import {validateApiGatewayEvent} from "openapi-request-validation"
export async function handler(event: unknown) {
validateApiGatewayEvent(validateCreateCustomerOrderRequest, event)
return {
statusCode: 204,
}
}Wrap route handlers with withLambdaApiValidation(...) or call validateLambdaApiRequest(...) directly.
import {validateCreateCustomerOrderRequest} from "./generated/openapi-validators.js"
import {withLambdaApiValidation} from "openapi-request-validation"
api.post(
"/customers/:customerId/orders",
withLambdaApiValidation(validateCreateCustomerOrderRequest, (req, res) => {
res.send({ok: true})
}),
)Wrap Express handlers with withExpressValidation(...) or call validateExpressRequest(...) directly.
import express from "express"
import {validateCreateCustomerOrderRequest} from "./generated/openapi-validators.js"
import {withExpressValidation} from "openapi-request-validation"
const app = express()
app.use(express.json())
app.post(
"/customers/:customerId/orders",
withExpressValidation(validateCreateCustomerOrderRequest, (req, res) => {
res.status(201).json({ok: true})
}),
)The runtime helpers throw RequestValidationError with HTTP status 400.
If your application already uses its own error type, pass createError in the optional runtime options:
import {validateExpressRequest} from "openapi-request-validation"
validateExpressRequest(validateCreateCustomerOrderRequest, req, {
createError: (message) => new BadRequestProblem(message),
})This repo uses the release-please flow for release automation.