I don't like swagger-jsdoc, but I like the other two. Tsoa is great but unfortunately I…
- User
I don't like swagger-jsdoc, but I like the other two. Tsoa is great but unfortunately I would have to rewrite the entire codebase for it to work, so I think swagger-autogen is my best option. Can you show more about it? I would like to know how it looks on a more complex endpoint, what version of openapi does it generate and can that then used by some sort of validator to validate requests and responses.
Assistant
Great! Let's dive deeper into swagger-autogen and address your specific questions. This tool is ideal for code-first API documentation, and it’s lightweight enough to integrate without rewriting your codebase. Here's how it works and what you can expect.
🔧 How swagger-autogen Works
- Scans your Express routes (e.g.,
app.get,app.post, etc.). - Extracts metadata from:
- Route paths
- Query parameters
- Request bodies
- Response examples
- JSDoc comments (optional)
- Generates an OpenAPI 3.0 spec (default) that you can use for documentation, validation, and more.
🧪 Example: Complex Endpoint with swagger-autogen
Here’s a realistic example of a POST endpoint with:
- A JSON body
- Query parameters
- Response examples
- Optional JSDoc comments
src/routes/users.ts/** * @route POST /users * @param {string} name.query - User name * @param {string} email.query - User email * @param {User} body - User data * @returns {User} 201 - Created user * @returns {Error} 400 - Invalid input */ app.post('/users', (req, res) => { const { name, email } = req.query; const { age, role } = req.body; // Simulate validation if (!name || !email || !age || !role) { return res.status(400).json({ error: 'Missing required fields' }); } const newUser = { id: 'u1', name, email, age, role }; res.status(201).json(newUser); });src/app.ts(main file)import express from 'express'; import { createSwaggerSpec } from 'swagger-autogen'; const app = express(); // Define your routes import './routes/users'; // Generate OpenAPI spec const doc = { info: { title: 'My API', version: '1.0.0', description: 'A complex API for user management', }, host: 'localhost:3000', schemes: ['http'], }; const outputFile = './swagger_output.json'; const endpointsFiles = ['./src/app.ts']; createSwaggerSpec(outputFile, endpointsFiles, doc).then(() => { app.listen(3000, () => console.log('Server running on http://localhost:3000')); });✅ Generated OpenAPI 3.0 Spec (simplified)
{ "openapi": "3.0.3", "info": { "title": "My API", "version": "1.0.0", "description": "A complex API for user management" }, "paths": { "/users": { "post": { "summary": "Create a new user", "parameters": [ { "in": "query", "name": "name", "schema": { "type": "string" } }, { "in": "query", "name": "email", "schema": { "type": "string" } } ], "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "age": { "type": "integer" }, "role": { "type": "string" } }, "required": ["age", "role"] } } } }, "responses": { "201": { "description": "Created user", "content": { "application/json": { "schema": { "type": "object", "properties": { "id": { "type": "string" }, "name": { "type": "string" }, "email": { "type": "string" }, "age": { "type": "integer" }, "role": { "type": "string" } } } } } }, "400": { "description": "Invalid input", "content": { "application/json": { "schema": { "type": "object", "properties": { "error": { "type": "string" } } } } } } } } } } }
📌 Key Features of swagger-autogen
1. OpenAPI Version
- Default: OpenAPI 3.0.3 (can be configured)
- Supports OpenAPI 3.1.x if needed (via
specVersionin config).
2. Validation
Once the spec is generated, you can:
- Use Swagger UI or Redoc for interactive documentation.
- Validate requests/responses against the spec using tools like:
- Ajv (JSON Schema validator)
- OpenAPI Validator (for full spec validation)
- Express middleware (e.g.,
express-openapi-validator)
Example: Validate with
express-openapi-validatornpm install express-openapi-validatorimport { ExpressOpenApiValidator } from 'express-openapi-validator'; app.use( ExpressOpenApiValidator({ apiSpec: './swagger_output.json', validateRequests: true, validateResponses: true, }) );This ensures all incoming requests and outgoing responses match the spec.
⚠️ Limitations of swagger-autogen
Feature Status TypeScript support Limited (relies on JSDoc comments) Full schema inference Partial (requires JSDoc hints for complex types) Custom security schemes Requires manual addition to the spec Nested objects Requires JSDoc comments for proper schema generation
🚀 Best Practices for Complex Endpoints
1. Use JSDoc Comments for Clarity
Add detailed comments to your routes to guide swagger-autogen:
/** * @route POST /users * @param {string} name.query - User name * @param {string} email.query - User email * @param {User} body - User data * @returns {User} 201 - Created user * @returns {Error} 400 - Invalid input */2. Define Models Explicitly
For complex types, define them in a separate file and reference them in your routes:
// src/models/user.ts export interface User { id: string; name: string; email: string; age: number; role: string; }Then reference them in your JSDoc comments:
/** * @param {User} body - User data */3. Use
swagger-autogenCLIRun it as part of your build process:
"scripts": { "generate-spec": "swagger-autogen -o ./swagger_output.json ./src/app.ts" }
🧩 Summary
Feature Details OpenAPI Version 3.0.3 (configurable) Validation Yes (via express-openapi-validatoror other tools)Complex Endpoints Supported with JSDoc comments TypeScript Partial (JSDoc required) Tooling swagger-autogen+express-openapi-validator
🛠️ Final Thoughts
If you want to avoid rewriting your codebase, swagger-autogen is a great choice. It’s low-effort and code-first, but you’ll need to add JSDoc comments for complex types and validation. For large APIs, this approach balances speed and maintainability.
Would you like a working example repo or help integrating this into your existing codebase? 🚀
- Scans your Express routes (e.g.,
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.