Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen3-30b-a3b· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

I don't like swagger-jsdoc, but I like the other two. Tsoa is great but unfortunately I…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with chatgpt-4o-latest-20250326’s answer.
  1. 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.

  2. Qwen 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 specVersion in 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-validator

    npm install express-openapi-validator
    
    import { 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

    FeatureStatus
    TypeScript supportLimited (relies on JSDoc comments)
    Full schema inferencePartial (requires JSDoc hints for complex types)
    Custom security schemesRequires manual addition to the spec
    Nested objectsRequires 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-autogen CLI

    Run it as part of your build process:

    "scripts": {
      "generate-spec": "swagger-autogen -o ./swagger_output.json ./src/app.ts"
    }
    

    🧩 Summary

    FeatureDetails
    OpenAPI Version3.0.3 (configurable)
    ValidationYes (via express-openapi-validator or other tools)
    Complex EndpointsSupported with JSDoc comments
    TypeScriptPartial (JSDoc required)
    Toolingswagger-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? 🚀

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.