在Debian系统上使用Swagger生成API文档,可按以下步骤操作:
安装工具
安装Node.js、npm及Swagger命令行工具:
sudo apt update
sudo apt install nodejs npm
sudo npm install -g swagger-jsdoc swagger-ui-express
编写Swagger配置文件
创建swagger.json
或swagger.yaml
,定义API规范(如端点、参数、响应模型等)。示例(JSON格式):
{
"openapi": "3.0.0",
"info": { "title": "Debian API", "version": "1.0.0" },
"paths": {
"/packages": {
"get": {
"summary": "获取Debian软件包列表",
"responses": {
"200": { "description": "软件包列表", "schema": { "type": "array", "items": { "type": "string" } } }
}
}
}
}
}
生成文档
使用swagger-jsdoc
生成HTML或其他格式文档:
swagger-jsdoc -i ./swagger.json -o ./docs
(若需启动本地预览服务器,可结合swagger-ui-express
在Express应用中配置,访问http://localhost:端口号/api-docs
查看)
集成到应用(可选)
在Debian的Node.js应用中,通过swagger-ui-express
将文档集成到API服务:
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));
app.listen(3000, () => console.log('服务已启动,文档可通过 /api-docs 访问'));
说明:
swagger-jsdoc
适合基于代码注释生成文档,swagger-codegen
适合从规范文件生成多语言客户端/服务端代码。