环境准备
sudo apt update && sudo apt install nodejs npm
。npm install swagger-ui-express swagger-jsdoc
。文档配置
swagger.json
或swagger.yaml
文件,定义API路径、参数、响应等,可使用Swagger Editor(https://editor.swagger.io/)编辑。{
"swagger": "2.0",
"info": {"title": "API文档", "version": "1.0.0"},
"basePath": "/api",
"paths": {
"/users": {
"get": {
"summary": "获取用户列表",
"responses": {"200": {"description": "用户列表"}}
}
}
}
}
集成到应用
app.js
中添加: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('服务运行在 http://localhost:3000/api-docs'));
反向代理(可选)
location /api-docs {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
}
版本管理
/api/v1/
、/api/v2/
,每个版本对应独立的Swagger配置文件。/api-docs?v=2
。自动化更新
安全与监控
文档优化
@example
注解提升可读性。swagger-ui-express
集成到现有Node.js服务。参考来源: