Swagger Node.js API Middleware Runner

raw JSON →
0.7.3 verified Thu Apr 23 auth: no javascript abandoned

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.

error Error: Cannot find module 'swagger-node-runner'
cause The 'swagger-node-runner' package is not installed or the path in your `require` statement is incorrect.
fix
Ensure the package is installed using 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 */ }
cause Your `swagger.yaml` or `swagger.json` file contains errors that violate the OpenAPI (Swagger 2.0) specification.
fix
Carefully review the validation error messages provided by the runner. Use a Swagger/OpenAPI editor (e.g., Swagger Editor online) to validate your API definition file and correct any syntax or schema issues.
error TypeError: Cannot read property 'parse' of undefined
cause This error often occurs when code written for older versions (pre-v0.6.0) that directly interacted with `swagger-tools` is run on v0.6.0 or newer, where `swagger-tools` has been replaced by `Sway`.
fix
Update your application code to use 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.
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.
fix Review the v0.6.0 release notes on GitHub for detailed upgrade instructions and adapt your code to `Sway`'s API or `swagger-node-runner`'s new middleware structure.
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.
fix Test your application thoroughly after upgrading to v0.7.0 to identify any regressions or behavioral changes due to `Sway 1.0`. Consult `Sway`'s release notes for specific breaking changes.
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.
fix Replace `cors` with `swagger-cors` in your middleware pipe (e.g., in `config/default.yaml`) and ensure your `fittingsDirs` configuration includes your `node_modules` path if `swagger-cors` is a direct dependency.
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.
fix Consider migrating to a modern OpenAPI/Swagger framework or middleware, such as `express-openapi`, `fastify-swagger`, or manually integrating `swagger-ui-express` with a routing library, to ensure ongoing support and security.
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.
fix Be aware that `x-private: true` tags will hide parts of your API from the served Swagger definition. If you need to override this, check the `privateTags` configuration option for `swagger_raw`.
npm install swagger-node-runner
yarn add swagger-node-runner
pnpm add swagger-node-runner

This quickstart demonstrates how to set up a basic Express application with `swagger-node-runner`. It loads an OpenAPI (Swagger 2.0) definition, registers the middleware for API routing and handling, and includes commented examples for a basic Swagger YAML file, a controller, and API key authentication.

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!');
  }
};
*/