JSPM

express-auto-swagger

1.1.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q66700F
  • License MIT

Automatically generate OpenAPI 3.0 specifications and serve Swagger UI for Express.js applications with zero configuration

Package Exports

  • express-auto-swagger
  • express-auto-swagger/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (express-auto-swagger) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

express-auto-swagger

npm version License: MIT Node.js CI

Automatically generate OpenAPI 3.0 specifications and serve Swagger UI for Express.js applications with zero configuration. Just like Swagger works in .NET, but for Node.js!

✨ Features

  • 🚀 Zero Configuration - Works out of the box with sensible defaults
  • 🔄 Automatic Route Discovery - Intercepts all Express routes automatically
  • 📖 Interactive Documentation - Serves Swagger UI for testing APIs
  • 📄 OpenAPI 3.0 Compliant - Generates valid OpenAPI specifications
  • Real-time Updates - Documentation updates as you add routes
  • 🎛️ Configurable - Customize titles, versions, and endpoint paths
  • 🛡️ Error Resilient - Graceful handling of edge cases
  • 📦 Lightweight - Minimal dependencies and overhead

🚀 Quick Start

Installation

npm install express-auto-swagger

Basic Usage

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();

// Initialize express-auto-swagger (must be called before defining routes)
autoSwagger(app);

// Define your routes as usual
app.get('/users', (req, res) => {
    res.json([{ id: 1, name: 'John Doe' }]);
});

app.post('/users', (req, res) => {
    res.status(201).json({ id: 2, name: 'Jane Smith' });
});

app.get('/users/:id', (req, res) => {
    res.json({ id: req.params.id, name: 'User Name' });
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
    console.log('📖 API Docs: http://localhost:3000/docs');
    console.log('📄 OpenAPI JSON: http://localhost:3000/openapi.json');
});

That's it! Your API documentation is now available at:

📖 Documentation

Configuration Options

const result = autoSwagger(app, {
    title: 'My API',           // API title (default: "API Documentation")
    version: '1.0.0',          // API version (default: "1.0.0")
    docsPath: '/api-docs',     // Swagger UI path (default: "/docs")
    jsonPath: '/openapi.json'  // OpenAPI JSON path (default: "/openapi.json")
});

Advanced Usage

The autoSwagger function returns an object with useful methods:

const swagger = autoSwagger(app, options);

// Access configuration
console.log(swagger.config);

// Get all discovered routes
console.log(swagger.getRoutes());

// Get generated OpenAPI specification
console.log(swagger.getSpec());

// Access the route registry directly
swagger.registry.addRoute('GET', '/custom-route');

Route Parameter Detection

express-auto-swagger automatically detects route parameters and includes them in the OpenAPI specification:

// This route:
app.get('/users/:userId/posts/:postId', handler);

// Generates OpenAPI with parameters:
// - userId (path parameter, required)
// - postId (path parameter, required)

Supported HTTP Methods

All standard Express HTTP methods are supported:

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH

Dynamic Route Registration

Routes added after initialization are automatically captured:

autoSwagger(app);

// Initial routes
app.get('/users', handler);

// Later in your application
setTimeout(() => {
    app.post('/posts', handler); // This will also be documented
}, 1000);

🎯 Examples

Basic REST API

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();
app.use(express.json());

autoSwagger(app, {
    title: 'User Management API',
    version: '1.0.0'
});

// CRUD operations
app.get('/users', (req, res) => res.json(users));
app.post('/users', (req, res) => res.status(201).json(newUser));
app.get('/users/:id', (req, res) => res.json(user));
app.put('/users/:id', (req, res) => res.json(updatedUser));
app.delete('/users/:id', (req, res) => res.status(204).send());

app.listen(3000);

Custom Configuration

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();

const swagger = autoSwagger(app, {
    title: 'My Custom API',
    version: '2.1.0',
    docsPath: '/documentation',
    jsonPath: '/api/spec.json'
});

app.get('/health', (req, res) => res.json({ status: 'ok' }));

app.listen(3000, () => {
    console.log(`Docs: http://localhost:3000${swagger.config.docsPath}`);
    console.log(`JSON: http://localhost:3000${swagger.config.jsonPath}`);
});

API Versioning

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();

autoSwagger(app, {
    title: 'Versioned API',
    version: '1.0.0'
});

// Version 1
const v1Router = express.Router();
v1Router.get('/users', (req, res) => res.json({ version: 'v1', users: [] }));
app.use('/api/v1', v1Router);

// Version 2
const v2Router = express.Router();
v2Router.get('/users', (req, res) => res.json({ version: 'v2', users: [] }));
app.use('/api/v2', v2Router);

app.listen(3000);

🔧 API Reference

autoSwagger(app, options)

Initializes express-auto-swagger for the given Express application.

Parameters:

  • app (Express Application) - The Express app instance
  • options (Object, optional) - Configuration options

Options:

  • title (string) - API documentation title (default: "API Documentation")
  • version (string) - API version (default: "1.0.0")
  • docsPath (string) - Swagger UI endpoint path (default: "/docs")
  • jsonPath (string) - OpenAPI JSON endpoint path (default: "/openapi.json")

Returns:

  • registry - Route registry instance
  • config - Resolved configuration object
  • getRoutes() - Function to get all discovered routes
  • getSpec() - Function to get the generated OpenAPI specification

Error Handling

express-auto-swagger is designed to be resilient and will not break your application:

  • Invalid route paths are skipped with warnings
  • Missing dependencies fall back gracefully
  • Configuration errors use safe defaults
  • Route registration errors are logged but don't stop the app

🛠️ Requirements

  • Node.js: 14.x or higher
  • Express: 4.x or higher
  • swagger-ui-express: 4.x or higher (automatically installed)

📦 Dependencies

express-auto-swagger has minimal dependencies:

  • swagger-ui-express - For serving the Swagger UI interface

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Development Setup

# Clone the repository
git clone https://github.com/shivomv/express-auto-swagger.git
cd express-auto-swagger

# Install dependencies
npm install

# Run tests
npm test

# Run examples
npm run example

Running Tests

# Run all tests
npm test

# Run specific test file
npm test -- test/specific-test.test.js

# Run tests with coverage
npm test -- --coverage

Running Examples

# Basic example
npm run example
# or
node example/app.js

# Advanced example
node example/advanced-example.js

# Minimal example
node example/minimal-example.js

📝 Changelog

v1.0.0

  • Initial release
  • Automatic route discovery
  • OpenAPI 3.0 specification generation
  • Swagger UI integration
  • Configurable endpoints and metadata
  • Comprehensive error handling
  • Full test coverage

🐛 Troubleshooting

Common Issues

Q: Swagger UI shows "Failed to load API definition" A: Make sure the OpenAPI JSON endpoint is accessible and returns valid JSON. Check the browser console for errors.

Q: Routes are not appearing in the documentation A: Ensure autoSwagger() is called before defining your routes. Routes defined before initialization won't be captured.

Q: Custom paths are not working A: Verify that custom paths start with / and don't conflict with existing routes.

Q: Getting "swagger-ui-express not found" warnings A: Install the peer dependency: npm install swagger-ui-express

Debug Mode

Enable debug logging by setting the environment variable:

DEBUG=express-auto-swagger node app.js

Getting Help

If you encounter issues:

  1. Check the examples directory for usage patterns
  2. Review the test files for expected behavior
  3. Search existing GitHub issues
  4. Create a new issue with a minimal reproduction case

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Inspired by Swagger integration in .NET applications
  • Built on top of the excellent swagger-ui-express package
  • Thanks to the Express.js community for the robust framework

Made with ❤️ for the Node.js community