auto-swagger-js
v1.0.3
Published
Auto Swagger UI generator for Express and REST APIs with zero config
Downloads
8
Maintainers
Readme
🧾 auto-swagger-js
🔥 Auto Swagger UI generator for Express.js REST APIs — with zero configuration.
✨ 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
:paramsyntax to Swagger{param}format - 🏷️ Smart tag generation from route segments (skips API prefixes)
- 🧾 Auto-generates request body schema for
POST,PUT, andPATCH - 🚀 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-expressis 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;
}): voidOptions
| 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:
- Extracting meaningful segments from route paths
- Skipping common API prefixes like
api,v1,v2, etc. - 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 UIGET /docs-json- Raw OpenAPI JSON specification
🐛 Troubleshooting
Routes Not Detected
Problem: Swagger shows "No operations defined in spec!"
Solutions:
- Ensure you call
autoSwagger()after defining/mounting all routes - Make sure you're using Express 4.x (not 5.x)
- 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 installRunning Tests
npm test📝 License
MIT License - see LICENSE file for details.
🧑💻 Author
Amire Joseph
- GitHub: @amirejoseph
- Email: [email protected]
🔮 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
