Swagger工具在Debian上的应用主要包括API文档管理、测试及代码生成,步骤如下:
安装工具
sudo apt update && sudo apt install nodejs npm
sudo npm install -g swagger-jsdoc swagger-ui-express
pip3 install swagger-editor swagger-codegen
创建配置文件
编写swagger.json
或swagger.yaml
定义API规范,例如:
{
"swagger": "2.0",
"info": {"title": "Sample API", "version": "1.0.0"},
"paths": {
"/users": {
"get": {
"summary": "List users",
"responses": {"200": {"description": "User list"}}
}
}
}
}
启动Swagger UI
swagger-ui-express
启动本地服务:swagger-ui-express --swagger-file=./swagger.yaml --port=8080
http://localhost:8080
查看文档。swagger-editor
,访问http://localhost:8000
。集成到应用
在Node.js项目中,通过swagger-ui-express
中间件集成到Express框架:
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('Server running on port 3000'));
生成客户端代码
使用Swagger Codegen生成指定语言的客户端代码:
swagger-codegen generate -i swagger.yaml -l python -o ./generated
。
说明:部分步骤中工具链选择存在差异(如swagger-jsdoc
与swagger-ui-express
的适用场景),建议根据实际需求选择工具链组合。