Senior LevelExpress JS
How do you implement Contract-First API development using express-openapi-validator?
❓ Interview Prompt: Explain Contract-First API development, OpenAPI 3.1 YAML specifications, and runtime request/response validation using express-openapi-validator.
In Contract-First API Development, teams write the OpenAPI 3.1 YAML specification before writing code.
Runtime Validation with 'express-openapi-validator':
Mount 'express-openapi-validator' at the top of your Express app:
•
Automatically validates all incoming 'req.body', 'req.params', and 'req.query' against the YAML spec.
•
Automatically validates outbound 'res.json()' payloads, ensuring your API never returns responses violating the public contract!
Code Implementation Example
javascript
import express from 'express';
import * as OpenApiValidator from 'express-openapi-validator';
import path from 'path';
const app = express();
app.use(express.json());
// Enforce OpenAPI 3.1 YAML contract validation at runtime!
app.use(
OpenApiValidator.middleware({
apiSpec: path.join(process.cwd(), 'openapi.yaml'),
validateRequests: true,
validateResponses: true // Ensures outbound responses match contract!
})
);💡Enforcing OpenAPI contract validation at runtime with express-openapi-validator.
🎯 Interview Key Takeaway
Use express-openapi-validator to enforce Contract-First OpenAPI YAML request and response validation at runtime.
#OpenAPI#Contract-First#Validation#Senior
Back to all Express JS Questions→