Skip to content

Operaconga14/auto-swagger-js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

3 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿงพ auto-swagger-js

Auto Swagger JS Logo

๐Ÿ”ฅ Auto Swagger UI generator for Express.js REST APIs โ€” with zero configuration.

NPM License Node


โœจ Features

  • ๐Ÿ“ฆ Zero-configuration โ€” no need to write JSDoc or decorators
  • ๐Ÿ” Automatically detects all routes and HTTP methods
  • ๐Ÿ”— Supports deeply nested routers with full path resolution
  • ๐Ÿง  Converts Express :param syntax to Swagger {param} format
  • ๐Ÿท๏ธ Smart tag generation from route segments (skips API prefixes)
  • ๐Ÿงพ Auto-generates request body schema for POST, PUT, and PATCH
  • ๐Ÿš€ Serves interactive Swagger UI at /docs
  • ๐Ÿ”ง Compatible with Express 4.x
  • ๐Ÿ“ฑ Interactive API testing directly in the browser

๐Ÿ“ฆ Installation

npm install auto-swagger-js swagger-ui-express

๐Ÿ”ง swagger-ui-express is a required peer dependency.


๐Ÿš€ Quick Start

Basic Usage

const express = require("express");
const autoSwagger = require("auto-swagger-js");

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

// Define your routes
app.get("/users/:id", (req, res) => {
    res.json({ id: req.params.id, name: "John Doe" });
});

app.post("/users", (req, res) => {
    res.json({ message: "User created", data: req.body });
});

// Generate Swagger docs AFTER defining routes
autoSwagger({
    app,
    title: "My API",
    version: "1.0.0",
});

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

With Modular Routes

const express = require("express");
const autoSwagger = require("auto-swagger-js");

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

// Import route modules
const userRoutes = require("./routes/users");
const productRoutes = require("./routes/products");

// Mount routes with prefixes
app.use("/api/v1/users", userRoutes);
app.use("/api/v1/products", productRoutes);

// Generate Swagger docs AFTER mounting routes
autoSwagger({
    app,
    title: "My E-commerce API",
    description:
        "A comprehensive e-commerce API with user and product management",
    version: "1.2.0",
    host: "api.mycompany.com",
    basePath: "/",
    schemes: ["https", "http"],
    securityDefinitions: {
        bearerAuth: {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
        },
    },
});

app.listen(3000, () => {
    console.log("API docs available at http://localhost:3000/docs");
});

Advanced Configuration Example

const express = require("express");
const autoSwagger = require("auto-swagger-js");

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

// Your routes here...
app.use("/api/v1/auth", authRoutes);
app.use("/api/v1/users", userRoutes);
app.use("/api/v1/orders", orderRoutes);

// Full configuration example
autoSwagger({
    app,
    title: "Enterprise API",
    description:
        "Enterprise-grade API for managing users, orders, and authentication",
    version: "2.1.0",
    host: "enterprise-api.example.com",
    basePath: "/api/v1",
    schemes: ["https"],
    securityDefinitions: {
        ApiKeyAuth: {
            type: "apiKey",
            in: "header",
            name: "X-API-Key",
        },
        BearerAuth: {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
        },
        OAuth2: {
            type: "oauth2",
            flows: {
                authorizationCode: {
                    authorizationUrl:
                        "https://auth.example.com/oauth/authorize",
                    tokenUrl: "https://auth.example.com/oauth/token",
                    scopes: {
                        read: "Read access",
                        write: "Write access",
                        admin: "Admin access",
                    },
                },
            },
        },
    },
    routePrefix: "/v1",
});

app.listen(443, () => {
    console.log("Secure API running on https://enterprise-api.example.com");
    console.log("Documentation: https://enterprise-api.example.com/docs");
});

๐Ÿ“š API Reference

Function Signature

autoSwagger(options: {
  app: Express.Application;
  title?: string;
  description?: string;
  version?: string;
  host?: string;
  basePath?: string;
  schemes?: string[];
  securityDefinitions?: object;
  routePrefix?: string;
}): void

Options

Option Type Default Description
app Express.Application (required) Your Express application instance
title string "Auto Swagger" Title for the Swagger UI
description string "Auto-generated API documentation" Description of your API
version string "1.0.0" API version string
host string "localhost:3000" Host where the API is served
basePath string "" Base path for all API endpoints
schemes string[] ["http"] Transfer protocols (http, https)
securityDefinitions object null Security definitions for authentication
routePrefix string "" Prefix to add to all route paths

๐Ÿงช Example Output

Input Routes

// routes/users.js
const router = express.Router();

router.get("/", (req, res) => {
    res.json({ message: "Get all users" });
});

router.get("/:id", (req, res) => {
    res.json({ id: req.params.id });
});

router.post("/", (req, res) => {
    res.json({ message: "User created" });
});

module.exports = router;

// main app
app.use("/api/v1/users", userRoutes);

Generated Swagger Spec

/api/v1/users:
    get:
        summary: GET /api/v1/users
        tags:
            - users
        responses:
            200:
                description: Success
    post:
        summary: POST /api/v1/users
        tags:
            - users
        requestBody:
            content:
                application/json:
                    schema:
                        type: object
                        properties: {}
        responses:
            200:
                description: Success

/api/v1/users/{id}:
    get:
        summary: GET /api/v1/users/:id
        tags:
            - users
        parameters:
            - in: path
              name: id
              required: true
              schema:
                  type: string
        responses:
            200:
                description: Success

๐Ÿท๏ธ Smart Tag Generation

Auto-swagger-js intelligently generates tags by:

  1. Extracting meaningful segments from route paths
  2. Skipping common API prefixes like api, v1, v2, etc.
  3. Using the first meaningful segment as the tag name

Examples:

Route Path Generated Tag
/api/v1/users users
/api/v2/products products
/v1/orders orders
/admin/settings admin

๐Ÿ”ง Advanced Features

Automatic Parameter Detection

Express route parameters like :id, :userId are automatically converted to Swagger path parameters:

// Express route
app.get("/users/:userId/posts/:postId", handler);

// Becomes Swagger path
("/users/{userId}/posts/{postId}");

Request Body Schema Generation

For POST, PUT, and PATCH methods, auto-swagger-js automatically adds a basic JSON request body schema:

requestBody:
    content:
        application/json:
            schema:
                type: object
                properties: {}

Nested Router Support

Supports complex nested routing structures:

const apiRouter = express.Router();
const v1Router = express.Router();
const userRouter = express.Router();

userRouter.get("/:id", handler);
v1Router.use("/users", userRouter);
apiRouter.use("/v1", v1Router);
app.use("/api", apiRouter);

// Results in: /api/v1/users/{id}

๐Ÿ“ Project Structure

auto-swagger-js/
โ”œโ”€โ”€ index.js               # Main entry point
โ”œโ”€โ”€ package.json           # Package configuration
โ”œโ”€โ”€ README.md             # This file
โ””โ”€โ”€ lib/
    โ”œโ”€โ”€ scanRoutes.js      # Route extraction from Express stack
    โ”œโ”€โ”€ extractParams.js   # Parameter conversion (:id โ†’ {id})
    โ”œโ”€โ”€ buildSwaggerSpec.js # OpenAPI specification builder
    โ””โ”€โ”€ serveSwaggerUI.js  # Swagger UI server setup

๐Ÿ”จ Requirements

  • Node.js: 14.x or higher
  • Express: 4.x (Express 5.x not supported yet)
  • swagger-ui-express: 4.x or 5.x

๐Ÿ“„ Endpoints

Auto-swagger-js automatically creates these endpoints:

  • GET /docs - Interactive Swagger UI
  • GET /docs-json - Raw OpenAPI JSON specification

๐Ÿ› Troubleshooting

Routes Not Detected

Problem: Swagger shows "No operations defined in spec!"

Solutions:

  1. Ensure you call autoSwagger() after defining/mounting all routes
  2. Make sure you're using Express 4.x (not 5.x)
  3. Check that route paths start with / (e.g., router.get("/users", ...))

Missing Tags

Problem: All routes show under same tag

Solution: Ensure your route structure has meaningful segments after API prefixes:

// Good: Will generate "users" tag
app.use("/api/v1/users", userRouter);

// Bad: Will generate "api" tag
app.use("/api", userRouter);

Path Parameter Issues

Problem: Parameters showing as :id instead of {id}

Solution: This is handled automatically. If you see this, please file an issue.


๐Ÿค Contributing

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

Development Setup

git clone https://github.com/Operaconga14/auto-swagger-js.git
cd auto-swagger-js
npm install

Running Tests

npm test

๐Ÿ“ License

MIT License - see LICENSE file for details.


๐Ÿง‘โ€๐Ÿ’ป Author

Amire Joseph


๐Ÿ”ฎ Roadmap

  • Express 5.x compatibility
  • Custom tag configuration
  • JSON schema auto-detection from middleware
  • CLI tool for exporting OpenAPI specs
  • Koa.js and Fastify support
  • Custom response schema definition
  • Authentication scheme detection

Made with โค๏ธ for the Express.js community

About

Auto Swagger UI generator for Express and REST APIs with zero config

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published