debian

Debian Swagger配置步骤

小樊
51
2025-09-21 07:56:52
栏目: 智能运维

1. 准备Debian系统环境
确保Debian系统已更新至最新版本,并安装Node.js(及npm,Node.js包管理器),这是Swagger工具运行的基础。

sudo apt update && sudo apt upgrade -y
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt install -y nodejs

2. 安装Swagger核心工具
通过npm全局安装swagger-jsdoc(用于从代码注释生成文档)和swagger-ui-express(用于在Express应用中集成Swagger UI)。

sudo npm install -g swagger-jsdoc swagger-ui-express

3. 创建Swagger配置文件
在项目根目录下创建swagger.yaml(或swagger.json)文件,定义API规范(包括端点、参数、响应模型等)。示例如下:

swagger: '2.0'
info:
  title: Sample API
  description: A demo API for Swagger configuration on Debian
  version: '1.0.0'
host: localhost:3000
basePath: /api
schemes:
  - http
paths:
  /users:
    get:
      summary: Retrieve all users
      responses:
        '200':
          description: A list of user objects
          schema:
            type: array
            items:
              $ref: '#/definitions/User'
definitions:
  User:
    type: object
    properties:
      id:
        type: string
      name:
        type: string
    required:
      - id
      - name

4. 集成Swagger到应用(以Express为例)
在Express应用中引入Swagger UI,将配置文件与接口关联。示例如下:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.yaml'); // 加载配置文件

const app = express();
const PORT = 3000;

// 集成Swagger UI到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

// 示例接口(需与swagger.yaml中的定义匹配)
app.get('/api/users', (req, res) => {
  res.json([
    { id: '1', name: 'John Doe' },
    { id: '2', name: 'Jane Smith' }
  ]);
});

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
  console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});

5. 启动应用并访问Swagger UI
运行Express应用,启动后通过浏览器访问http://localhost:3000/api-docs,即可看到Swagger UI界面。在该界面中,你可以查看API文档、测试端点(如点击“Try it out”按钮发送请求)。

node app.js

注意事项

0
看了该问题的人还看了