Swagger Node.js API Middleware Runner
raw JSON →swagger-node-runner is a middleware engine designed to integrate Swagger (now OpenAPI) definitions with various Node.js web frameworks, including Connect, Express, Restify, Hapi, and Sails. It handles the loading and processing of API definitions, routing, and applying middleware based on the specification. The package is currently at version 0.7.3, with its last known release in October 2016. Its primary differentiation from earlier solutions was the complete replacement of `swagger-tools` with the `Sway` library starting from version 0.6.0, which was further updated to `Sway 1.0` in version 0.7.0. Due to its age and lack of recent updates, the project appears to be abandoned, meaning it does not receive new features, bug fixes, or security patches. Developers should exercise caution regarding its compatibility with modern Node.js versions and potential security vulnerabilities in its outdated dependencies.
Common errors
error Error: Cannot find module 'swagger-node-runner' ↓
npm install swagger-node-runner and that your require('swagger-node-runner') statement points to the correct module. error Swagger validation failed: { /* details about validation errors */ } ↓
error TypeError: Cannot read property 'parse' of undefined ↓
swagger-node-runner's new API methods or Sway's API for parsing and validation, as direct calls to swagger-tools functionality are no longer supported by swagger-node-runner itself. Warnings
breaking Version 0.6.0 completely replaced `swagger-tools` with the `Sway` library for Swagger/OpenAPI parsing and validation. Projects upgrading from versions prior to 0.6.0 must follow specific upgrade instructions, as direct API calls to `swagger-tools` will no longer work. ↓
breaking Version 0.7.0 upgraded the underlying `Sway` library to `Sway 1.0`. While release notes primarily mentioned enhancements and fixes, a major version bump of a core dependency often introduces breaking changes or significant behavioral shifts that may impact existing implementations. ↓
gotcha The `cors` fitting was deprecated in favor of `swagger-cors` in version 0.7.1. If you are using the `cors` fitting, you should consider migrating to `swagger-cors` for potential enhancements and better integration. ↓
gotcha The package `swagger-node-runner` is effectively abandoned, with its last release in October 2016. This means it no longer receives bug fixes, new features, or security updates. Using it in production carries risks of unpatched vulnerabilities and compatibility issues with newer Node.js versions or dependencies. ↓
gotcha The `swagger_raw` fitting gained support for `x-private: true` tags in v0.6.11. Objects (like paths or operations) marked with this tag in your Swagger definition will be excluded from the served Swagger API, which might lead to unexpected behavior if not understood. ↓
Install
npm install swagger-node-runner yarn add swagger-node-runner pnpm add swagger-node-runner Imports
- create wrong
import { create } from 'swagger-node-runner';correctconst runner = require('swagger-node-runner').create(config); - SwaggerUI wrong
const swaggerUi = require('swagger-node-runner').swaggerUi;correctconst swaggerTools = require('swagger-tools'); // Only if using v0.5.x or older - ConfigObject wrong
const config = new SwaggerNodeRunner.Config();correctconst config = { appRoot: __dirname, swaggerFile: '/path/to/swagger.yaml' };
Quickstart
const express = require('express');
const SwaggerNodeRunner = require('swagger-node-runner');
const path = require('path');
const app = express();
const port = process.env.PORT || 3000;
// Configuration for swagger-node-runner
const config = {
appRoot: __dirname, // Tells swagger-node-runner where to find controllers and fittings
swaggerFile: path.resolve(__dirname, 'api', 'swagger', 'swagger.yaml'),
// Example of a security handler configuration (uncomment and customize if needed)
// swaggerSecurityHandlers: {
// ApiKeyAuth: function (req, authOrSecDef, scopes, callback) {
// // Simulate API key validation using an environment variable
// if (req.headers['x-api-key'] === (process.env.API_KEY || 'your-secret-key')) {
// callback();
// } else {
// callback(new Error('Access denied: Invalid API Key'));
// }
// }
// }
};
SwaggerNodeRunner.create(config, function (err, runner) {
if (err) { throw err; }
// Install the Swagger Express middleware provided by the runner
runner.expressMiddleware().register(app);
// For Swagger UI, you would typically use a separate package (e.g., swagger-ui-express)
// Example: app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(runner.swagger.parsed));
app.listen(port, function () {
console.log(`Your API is running at http://localhost:${port}`);
console.log(`Swagger UI (if configured separately) would be available at /api-docs`);
});
});
// --- Minimal example files to make the above code runnable ---
// Save this as api/swagger/swagger.yaml:
/*
swagger: '2.0'
info:
title: Example API
version: '1.0.0'
basePath: /v1
paths:
/hello:
x-swagger-router-controller: hello_world
get:
description: Returns 'Hello, World!'
operationId: hello
responses:
'200':
description: Success
schema:
type: string
*/
// Save this as api/controllers/hello_world.js:
/*
module.exports = {
hello: function (req, res) {
res.json('Hello, World!');
}
};
*/