You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js Express Router集成Swagger:如何自动生成接口文档?

Auto-Generating Swagger Docs for Express Router (Like Spring WebServices)

Absolutely! For Express-based Node.js projects, there are several solid tools that let you auto-generate Swagger/OpenAPI documentation just like Spring WebServices does—no more manually updating JSON/YAML files every time you tweak an endpoint. Let’s break down the most popular approaches tailored for Express Router:

1. swagger-jsdoc + swagger-ui-express (JavaScript/TypeScript)

This is the go-to combo for most Express projects. It uses JSDoc-style comments directly in your route code to define API metadata, then auto-generates the full OpenAPI spec.

Setup Steps:

  • Install dependencies:
    npm install swagger-jsdoc swagger-ui-express
    
  • Configure Swagger in your main Express file:
    const swaggerJsdoc = require('swagger-jsdoc');
    const swaggerUi = require('swagger-ui-express');
    
    // Define base OpenAPI info
    const swaggerOptions = {
      definition: {
        openapi: '3.0.0',
        info: {
          title: 'My Express API',
          version: '1.0.0',
          description: 'Auto-generated docs using swagger-jsdoc',
        },
      },
      // Point to files containing JSDoc API comments
      apis: ['./routes/*.js'],
    };
    
    // Generate the spec
    const swaggerSpec = swaggerJsdoc(swaggerOptions);
    
    // Mount Swagger UI at /api-docs
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
    
  • Add JSDoc comments to your Express Router routes:
    /**
     * @swagger
     * /api/users:
     *   get:
     *     summary: Fetch all users
     *     description: Returns a list of all registered users
     *     responses:
     *       200:
     *         description: Success
     *         content:
     *           application/json:
     *             schema:
     *               type: array
     *               items:
     *                 type: object
     *                 properties:
     *                   id:
     *                     type: integer
     *                   name:
     *                     type: string
     */
    router.get('/api/users', (req, res) => {
      // Your route logic here
      res.json([{ id: 1, name: 'John Doe' }]);
    });
    

Start your server, visit /api-docs, and you’ll see your auto-generated docs!

2. TSOA (TypeScript-Only)

If you’re using TypeScript, TSOA is a fantastic option that mirrors Spring’s approach closely. It uses TypeScript decorators and type definitions to auto-generate both OpenAPI docs and Express routes—no manual routing setup needed.

Setup Steps:

  • Install dependencies:
    npm install tsoa swagger-ui-express
    
  • Define a controller with decorators:
    import { Get, Route, Tags } from 'tsoa';
    
    @Route('users') // Base route path
    @Tags('Users') // Group docs under "Users"
    export class UsersController {
      @Get('/') // HTTP method + subpath
      public async getUsers(): Promise<Array<{ id: number; name: string }>> {
        return [{ id: 1, name: 'John Doe' }];
      }
    }
    
  • Add a tsoa.json config file (adjust paths to match your project):
    {
      "entryFile": "./src/server.ts",
      "noImplicitAdditionalProperties": "throw-on-extras",
      "controllerPathGlobs": ["src/controllers/**/*.ts"],
      "spec": {
        "outputDirectory": "./src",
        "specVersion": 3
      },
      "routes": {
        "routesDir": "./src/routes"
      }
    }
    
  • Generate routes and Swagger spec:
    tsoa routes && tsoa spec
    
  • Mount the generated routes and Swagger UI in your Express app:
    import { RegisterRoutes } from './routes';
    import swaggerUi from 'swagger-ui-express';
    import swaggerDocument from './swagger.json';
    
    // Auto-register all controller routes
    RegisterRoutes(app);
    // Serve Swagger docs
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    

3. swagger-autogen + express-openapi-validator (Minimal Comments)

If you want to avoid writing too much JSDoc, swagger-autogen can scan your Express routes and generate a basic OpenAPI spec automatically. You can then tweak the spec manually, and use express-openapi-validator to add request/response validation.

Setup Steps:

  • Install dependencies:
    npm install swagger-autogen express-openapi-validator swagger-ui-express
    
  • Generate a base Swagger spec:
    const swaggerAutogen = require('swagger-autogen')();
    
    const doc = {
      info: {
        title: 'My API',
        description: 'Auto-generated base spec',
      },
      host: 'localhost:3000',
      schemes: ['http'],
    };
    
    const outputFile = './swagger-output.json';
    const endpointFiles = ['./routes/*.js'];
    
    // Generate the spec
    swaggerAutogen(outputFile, endpointFiles, doc);
    
  • Mount Swagger UI and validation middleware:
    const { OpenApiValidator } = require('express-openapi-validator');
    const swaggerUi = require('swagger-ui-express');
    const swaggerDocument = require('./swagger-output.json');
    
    app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
    
    // Add API validation (optional but recommended)
    app.use(
      OpenApiValidator.middleware({
        apiSpec: swaggerDocument,
        validateRequests: true,
        validateResponses: false,
      })
    );
    

All these tools eliminate the need for manual JSON/YAML maintenance, just like Spring’s auto-doc generation. Pick the one that fits your project’s tech stack (JS vs TS) and workflow preferences!

内容的提问来源于stack exchange,提问作者Sharan De Silva

火山引擎 最新活动