以下是在Debian上集成Swagger的教程:
更新系统并安装Node.js、npm和Swagger相关工具:
sudo apt update && sudo apt install nodejs npm
sudo npm install -g swagger-jsdoc swagger-ui-express
在项目目录创建swagger.json
或swagger.yaml
文件,定义API规范,如:
{
"swagger": "2.0",
"info": {
"title": "Sample API",
"version": "1.0.0"
},
"basePath": "/api",
"paths": {
"/users": {
"get": {
"summary": "List all users",
"responses": {
"200": {
"description": "An array of users"
}
}
}
}
}
}
以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));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
启动应用后,访问http://localhost:3000/api-docs
可查看Swagger UI界面及测试API。