在Debian中使用Swagger进行API文档共享的步骤
首先确保Debian系统更新至最新状态,并安装Node.js、npm(Node.js包管理器)及Python3 pip(用于后续可能的Python项目依赖)。
sudo apt update && sudo apt upgrade -y
sudo apt install -y nodejs npm python3-pip
使用npm全局安装Swagger UI Express(用于快速集成Swagger UI到Web应用)和swagger-jsdoc(用于从代码注释生成Swagger文档):
sudo npm install -g swagger-ui-express swagger-jsdoc
在项目根目录下创建swagger.yaml(或swagger.json)文件,定义API的核心规范(如标题、版本、主机、路径等)。以下是一个示例:
swagger: '2.0'
info:
title: Sample API
description: A demo API for Swagger documentation sharing
version: '1.0.0'
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: List all users
responses:
'200':
description: A list of user objects
schema:
type: array
items:
$ref: '#/definitions/User'
definitions:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
email:
type: string
format: email
required:
- id
- name
创建项目目录并初始化package.json:
mkdir swagger-demo && cd swagger-demo
npm init -y
安装Express框架及Swagger相关中间件:
npm install express swagger-ui-express yamljs
创建app.js文件,加载Swagger文档并设置文档访问路由:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
// 加载Swagger文档(YAML格式)
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
// 将Swagger UI挂载到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 示例API端点(需与swagger.yaml中的路径一致)
app.get('/api/users', (req, res) => {
res.json([
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
]);
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});
启动Node.js服务器:
node app.js
打开浏览器,访问http://<服务器IP>:3000/api-docs(若为本地测试则为http://localhost:3000/api-docs),即可看到Swagger UI界面。通过该界面可:
/users)的详细说明;在app.js中修改Swagger UI配置,例如开启深度链接、更改主题:
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
deepLinking: true,
theme: 'dark', // 或 'light'
presets: [swaggerUi.presets.apis, swaggerUi.presets.topbar]
}));
使用swagger-jsdoc从代码注释生成Swagger文档(适用于大型项目)。在app.js中添加:
const swaggerSpec = swaggerJsdoc({
definition: {
info: {
title: 'Sample API',
version: '1.0.0'
},
basePath: '/api'
},
apis: ['./routes/*.js'] // 指定包含JSDoc注释的路由文件路径
});
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
通过环境变量限制文档访问(如仅允许内部IP):
const SWAGGER_ENABLED = process.env.SWAGGER_ENABLED === 'true';
if (SWAGGER_ENABLED) {
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
}
启动时设置环境变量:
SWAGGER_ENABLED=true node app.js
flask-swagger-ui或django-rest-swagger等库集成Swagger;