ubuntu

如何使用Ubuntu Swagger生成API文档

小樊
40
2025-08-09 05:07:32
栏目: 智能运维

在Ubuntu上使用Swagger生成API文档,可参考以下步骤:

  1. 安装Swagger工具:基于Debian的系统(如Ubuntu),使用命令sudo apt updatesudo apt install swagger-jsdoc swagger-ui-express安装。
  2. 配置Swagger:创建swagger.jsonswagger.yaml文件,定义API元数据,如路径、操作、参数等。例如:
{
    "swagger": "2.0",
    "info": {
        "description": "Sample API",
        "version": "1.0.0"
    },
    "basePath": "/api",
    "paths": {
        "/users": {
            "get": {
                "summary": "List all users",
                "responses": {
                    "200": {
                        "description": "An array of users",
                        "schema": {
                            "type": "array",
                            "items": {
                                "$ref": "#/definitions/User"
                            }
                        }
                    }
                }
            }
        }
    },
    "definitions": {
        "User": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "integer"
                },
                "name": {
                    "type": "string"
                }
            }
        }
    }
}
  1. 集成Swagger到应用:若使用Express框架,可通过以下代码集成Swagger UI:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
  1. 生成API文档:运行Node.js应用,访问http://localhost:3000/api-docs(端口可自定义),即可查看Swagger UI界面中的API文档。

0
看了该问题的人还看了