npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

swagger-express-automate

v1.0.5

Published

Express.js üçün flexible Swagger API sənədləşdirmə generatoru - 4 fərqli istifadə üsulu

Readme

🚀 Swagger Express Automate

The most flexible Swagger API documentation package for Express.js. Use it in 4 different ways!

⚡ Installation

npm install swagger-express-automate

🎯 Key Features

4 different usage methods - choose what fits you best
Router auto-scan - automatic documentation with app.use()
Decorator pattern - add metadata separately
Manual API - full control for those who need it
Group support - create route groups
Middleware friendly - works with any middleware


📖 Usage Methods

🔹 Method 1: Router Scan (Simplest)

Create your routers and just scan them:

const express = require('express');
const SwaggerAutomate = require('swagger-express-automate');

const app = express();
const swagger = new SwaggerAutomate(app, {
  title: 'My API',
  version: '1.0.0'
});

const userRouter = express.Router();
userRouter.get('/', (req, res) => res.json([{ id: 1, name: 'John' }]));
userRouter.post('/', (req, res) => res.json(req.body));
userRouter.get('/:id', (req, res) => res.json({ id: req.params.id }));

app.use('/api/users', swagger.middleware(userRouter), userRouter);

swagger.setupSwaggerUI('/docs');

✨ Automatic:

  • All routes are scanned
  • Path parameters auto-detected
  • Default documentation generated

🔹 Method 2: Scan + Metadata

Scan routes first, then add metadata:

app.use('/api/users', swagger.middleware(userRouter), userRouter);

swagger
  .doc('GET', '/api/users', {
    summary: 'Get all users',
    tags: ['Users'],
    responses: {
      200: {
        description: 'User list',
        content: {
          'application/json': {
            schema: {
              type: 'array',
              items: swagger.createSchema({
                id: { type: 'integer' },
                name: { type: 'string' },
                email: { type: 'string' }
              })
            }
          }
        }
      }
    }
  })
  .doc('POST', '/api/users', {
    summary: 'Create new user',
    tags: ['Users'],
    security: [{ BearerAuth: [] }],
    requestBody: swagger.createRequestBody(
      swagger.createSchema({
        name: { type: 'string', example: 'John Doe' },
        email: { type: 'string', example: '[email protected]' }
      }, ['name', 'email'])
    )
  });

✨ Benefits:

  • Routes and documentation are separated
  • Add metadata without changing existing code
  • Cleaner and more modular

🔹 Method 3: Manual API

Routes and documentation together:

swagger.post('/api/products', (req, res) => {
  res.status(201).json(req.body);
}, {
  summary: 'Create new product',
  tags: ['Products'],
  security: [{ BearerAuth: [] }],
  requestBody: swagger.createRequestBody(
    swagger.createSchema({
      name: { type: 'string', example: 'Laptop' },
      price: { type: 'number', example: 1500 },
      category: { type: 'string', example: 'Electronics' }
    }, ['name', 'price'])
  ),
  responses: {
    ...swagger.createResponse(201, 'Product created'),
    ...swagger.createResponse(400, 'Invalid data')
  }
});

swagger.get('/api/products/:id', handler, config);
swagger.put('/api/products/:id', handler, config);
swagger.delete('/api/products/:id', handler, config);

✨ Ideal for:

  • Small APIs
  • Quick prototypes
  • When documentation and code should be together

🔹 Method 4: Group Pattern

Create route groups:

swagger.group('/api/auth', (api) => {
  api.post('/login', (req, res) => {
    res.json({ token: 'jwt_token_here' });
  }, {
    summary: 'User login',
    tags: ['Auth'],
    requestBody: api.createRequestBody(
      api.createSchema({
        email: { type: 'string', format: 'email' },
        password: { type: 'string', format: 'password' }
      }, ['email', 'password'])
    )
  });

  api.post('/register', registerHandler, config);
  api.post('/logout', logoutHandler, config);
  api.post('/refresh', refreshHandler, config);
});

✨ Benefits:

  • Organized code
  • No prefix repetition
  • Common configuration for the same group

🛠️ Helper Methods

Create Schema

const userSchema = swagger.createSchema({
  id: { type: 'integer', example: 1 },
  name: { type: 'string', example: 'John' },
  email: { type: 'string', format: 'email', example: '[email protected]' },
  age: { type: 'integer', minimum: 0, example: 25 }
}, ['name', 'email']); // required fields

Create Parameter

swagger.createParameter(
  'id',           // name
  'path',         // location: 'path', 'query', 'header', 'cookie'
  'integer',      // type
  true,           // required
  'User ID'       // description
)

Create Request Body

swagger.createRequestBody(
  schema,
  'Request body description',
  true // required
)

Create Response

swagger.createResponse(
  200,
  'Successful operation',
  responseSchema
)

🔐 Authentication

Configure JWT and other authentication types:

const swagger = new SwaggerAutomate(app, {
  title: 'Secure API',
  securityDefinitions: {
    BearerAuth: {
      type: 'http',
      scheme: 'bearer',
      bearerFormat: 'JWT'
    },
    ApiKeyAuth: {
      type: 'apiKey',
      in: 'header',
      name: 'X-API-Key'
    },
    OAuth2: {
      type: 'oauth2',
      flows: {
        authorizationCode: {
          authorizationUrl: 'https://example.com/oauth/authorize',
          tokenUrl: 'https://example.com/oauth/token',
          scopes: {
            'read': 'Read access',
            'write': 'Write access'
          }
        }
      }
    }
  }
});

swagger.get('/api/protected', handler, {
  summary: 'Protected endpoint',
  security: [{ BearerAuth: [] }]
});

🏷️ Tags and Groups

const swagger = new SwaggerAutomate(app, {
  title: 'E-Commerce API',
  tags: [
    {
      name: 'Users',
      description: 'User operations'
    },
    {
      name: 'Products',
      description: 'Product operations',
      externalDocs: {
        description: 'Learn more',
        url: 'https://docs.example.com/products'
      }
    },
    {
      name: 'Orders',
      description: 'Order operations'
    }
  ]
});

🌐 Multi-Server Support

const swagger = new SwaggerAutomate(app, {
  servers: [
    {
      url: 'https://api.example.com/v1',
      description: 'Production server'
    },
    {
      url: 'https://staging.example.com/v1',
      description: 'Staging server'
    },
    {
      url: 'http://localhost:3000/api',
      description: 'Development server'
    }
  ]
});

📦 Complete Example

const express = require('express');
const SwaggerAutomate = require('swagger-express-automate');

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

const swagger = new SwaggerAutomate(app, {
  title: 'E-Commerce API',
  version: '2.0.0',
  description: 'Fully functional e-commerce API',
  host: 'localhost:3000',
  basePath: '/api',
  tags: [
    { name: 'Products', description: 'Product operations' },
    { name: 'Users', description: 'User operations' }
  ],
  securityDefinitions: {
    BearerAuth: {
      type: 'http',
      scheme: 'bearer',
      bearerFormat: 'JWT'
    }
  }
});

const productRouter = express.Router();

productRouter.get('/', (req, res) => {
  res.json([
    { id: 1, name: 'Laptop', price: 1500 },
    { id: 2, name: 'Phone', price: 800 }
  ]);
});

productRouter.post('/', (req, res) => {
  res.status(201).json(req.body);
});

productRouter.get('/:id', (req, res) => {
  res.json({ id: req.params.id, name: 'Laptop', price: 1500 });
});

app.use('/api/products', swagger.middleware(productRouter), productRouter);

const productSchema = swagger.createSchema({
  id: { type: 'integer', example: 1 },
  name: { type: 'string', example: 'Gaming Laptop' },
  price: { type: 'number', format: 'float', example: 2499.99 },
  category: { type: 'string', example: 'Electronics' }
}, ['name', 'price']);

swagger
  .doc('GET', '/api/products', {
    summary: 'Get all products',
    tags: ['Products'],
    parameters: [
      swagger.createParameter('category', 'query', 'string', false, 'Category filter'),
      swagger.createParameter('minPrice', 'query', 'number', false, 'Minimum price')
    ]
  })
  .doc('POST', '/api/products', {
    summary: 'Create new product',
    tags: ['Products'],
    security: [{ BearerAuth: [] }],
    requestBody: swagger.createRequestBody(productSchema),
    responses: {
      ...swagger.createResponse(201, 'Product created', productSchema),
      ...swagger.createResponse(400, 'Invalid data'),
      ...swagger.createResponse(401, 'Authentication required')
    }
  });

swagger.setupSwaggerUI('/docs');

app.listen(3000, () => {
  console.log('🚀 Server: http://localhost:3000');
  console.log('📖 Docs: http://localhost:3000/docs');
});

🎨 Decision Guide

| Method | Ideal For | Advantages | |------|----------|-----------| | Router Scan | Large projects, existing codebase | Fast, minimal changes | | Scan + Metadata | Medium/large projects | Flexible, clean code | | Manual API | Small projects, prototypes | Simple, everything together | | Group Pattern | API versioning, modular code | Organized, readable |


📝 License

MIT

🤝 Contributing

Pull requests are welcome! For major changes, please open an issue first.


Built with ❤️ for Express.js and Swagger users