Skip to content
The Chat Archive
chatgpt-4o-latest-20250326· OpenAI LMArena Human Preference 140K

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

  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. Assistant

    Great choice! swagger-autogen is an excellent low-effort tool that lets you auto-generate OpenAPI docs from your existing Express routes. It's particularly handy when you don't want to do a full rewrite (like you would with tsoa), but still want detailed output.

    Let's break down what you asked:


    ✅ Overview of swagger-autogen

    🔧 What is it?

    swagger-autogen parses your existing Express+TypeScript (or JS) routes, reads comments, and automatically generates an OpenAPI (Swagger) spec from it.

    • Uses inline JS/TS comments for doc hints.
    • Generates a complete swagger_output.json OpenAPI file.
    • Can be used with Swagger UI, ReDoc, Postman, etc.
    • Very low intrusion: you don’t change how your routes are written much.

    📜 OpenAPI Version Support

    As of the latest version (v2.23.2 — check package.json), swagger-autogen generates OpenAPI 3.0.0 specs.

    • ✅ Compatible with Swagger UI, Redoc, openapi-generator, validators like openapi-backend, Prism, and many others.

    💡 Example of a More "Complex" Endpoint

    /**
     * @swagger
     * /products/{id}:
     *   get:
     *     summary: Get product by ID
     *     parameters:
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *     responses:
     *       200:
     *         description: Product found
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/Product'
     *       404:
     *         description: Product not found
     */
    app.get('/products/:id', (req, res) => {
      const id = req.params.id;
      // #swagger.tags = ['Products']
      // #swagger.description = 'Get info about a specific product.'
      // #swagger.parameters['id'] = { description: 'Product ID' }
      // #swagger.responses[200] = {
      //     description: 'Product schema response',
      //     schema: { "$ref": "#/definitions/Product" }
      // }
      // #swagger.responses[404] = { description: 'Not found' }
    
      // Simulated business logic...
      const product = findProductById(id);
      if (!product) return res.status(404).send();
      return res.json(product);
    });
    

    You use special inline comments:

    • // #swagger.tags, // #swagger.description
    • // #swagger.responses[...]
    • Also supports request bodies: // #swagger.requestBody = { ... }

    You still write business logic the same as before – just sprinkle in some documentation hints.


    🔃 Steps to Set It Up

    1. Install:

    npm install swagger-autogen swagger-ui-express
    

    (assuming you already use Express)


    2. Create a swagger.js or swagger.ts build script:

    // swagger.ts
    import swaggerAutogen from 'swagger-autogen';
    
    const doc = {
      info: {
        title: 'My API',
        description: 'Automatically generated by swagger-autogen',
        version: '1.0.0',
      },
      host: 'localhost:3000',
      schemes: ['http'],
      definitions: {
        Product: {
          id: 'p123',
          name: 'Keyboard',
          price: 29.99,
        },
      },
    };
    
    const outputFile = './swagger_output.json';
    const endpointsFiles = ['./src/routes/products.ts'];
    
    swaggerAutogen({ openapi: '3.0.0' })(outputFile, endpointsFiles, doc);
    

    👉 Run it with:

    ts-node swagger.ts
    # OR (if you compiled to JS)
    node swagger.js
    

    This builds your swagger_output.json.


    3. Serve Docs

    import swaggerUi from 'swagger-ui-express';
    import swaggerDocument from './swagger_output.json';
    
    app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    

    And go to:
    http://localhost:3000/docs


    ✅ Validation of Requests/Responses?

    swagger-autogen itself does not validate requests/responses.

    But once it generates an OpenAPI 3.0 spec, you can use it with separate tooling to add schema validation & contract testing:

    ✅ Options:

    ToolPurposeNotes
    🔍 PrismMock server, validator, proxyValidates live requests/responses against OpenAPI schema
    ⚖️ express-openapi-validatorMiddleware validatorLoad OpenAPI JSON, adds full validation
    🧪 DreddTest spec vs real appRun contract tests from a Swagger/OpenAPI file

    ✅ Example: Use express-openapi-validator

    npm install express-openapi-validator
    

    In your Express app:

    import OpenApiValidator from 'express-openapi-validator';
    
    // Load the generated spec
    app.use(
      OpenApiValidator.middleware({
        apiSpec: './swagger_output.json',
        validateRequests: true,     // <- Validate incoming query/body
        validateResponses: true,    // <- Validate res.json() against schema
      })
    );
    
    // Your routes go here now
    app.use('/products', productRouter);
    

    Now if someone sends:

    • A missing required query param
    • An invalid POST body
    • Your route returns a wrongly-shaped response...

    💥 It will throw a structured OpenAPI error (can be formatted for the client).


    😎 TL;DR

    FeatureYes / No
    Uses existing Express+TS code✅ Yes
    Generates OpenAPI 3.0✅ Yes
    Supports inline route documentation✅ Yes
    Low-intrusion in existing code✅ Excellent
    Output usable by external tools✅ Yes (Swagger UI, Redoc, validators)
    Supports request/response schemas✅ Yes (via inline comments)
    Can validate requests/responses🚫 Not built in → use express-openapi-validator

    👣 Next Steps

    • Write a few routes with inline docs
    • Auto-generate the spec
    • Add express-openapi-validator → now you’ve got live contract validation

    If you'd like, I can give you a full working repo or template with swagger-autogen + validator middleware + Swagger UI ready to go!

    Let me know 😊

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