ubuntu

如何编写ubuntu swagger API文档

小樊
46
2025-11-06 11:33:02
栏目: 智能运维

在Ubuntu上编写Swagger API文档的步骤

1. 准备基础环境

在Ubuntu系统上,首先需要安装Node.js和npm(Node.js包管理器),这是使用Swagger Editor、Swagger UI等工具的前提。打开终端,执行以下命令:

sudo apt update
sudo apt install -y nodejs npm

安装完成后,可通过nodejs -vnpm -v验证安装是否成功。

2. 安装Swagger核心工具

2.1 安装Swagger Editor(可视化编写规范)

Swagger Editor是Swagger生态中的在线/本地编辑工具,支持YAML/JSON格式的OpenAPI规范编写。通过npm全局安装:

sudo npm install -g swagger-editor-cli

安装完成后,启动本地编辑器实例:

swagger-editor-cli start

这会在默认浏览器中打开Swagger Editor(通常为http://localhost:8080),可直接在线编写或导入现有规范文件。

2.2 安装Swagger UI(可视化展示文档)

Swagger UI用于将OpenAPI规范转换为交互式网页文档,方便测试接口。若项目基于Node.js,可通过npm安装:

npm install -g swagger-ui-express

后续需结合Express框架集成到项目中(见步骤3)。

3. 编写OpenAPI规范文件

OpenAPI规范(OAS)是Swagger文档的基础,定义了API的端点、参数、响应、认证等信息。可通过以下两种方式创建:

3.1 使用Swagger Editor编写

打开Swagger Editor后,在左侧编辑区输入YAML格式的规范(示例如下),右侧会实时预览文档效果。完成后点击“Save”保存为swagger.yamlswagger.json文件。

openapi: 3.0.0
info:
  title: Sample API
  version: 1.0.0
  description: A simple API for demonstration
paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string

3.2 手动创建文件

使用文本编辑器(如vimnano)直接创建YAML文件,内容参考上述示例。保存至项目目录(如./docs/swagger.yaml)。

4. 集成Swagger UI到项目(可选,适用于Web应用)

若项目是基于Node.js的Web应用(如Express),可将Swagger UI集成到应用中,实现文档与应用的联动。示例如下:

4.1 安装依赖

npm install swagger-ui-express yamljs

4.2 编写集成代码

在Express应用的主文件(如app.js)中添加以下代码:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

const app = express();
// 读取OpenAPI规范文件
const swaggerDocument = YAML.load('./docs/swagger.yaml');
// 集成Swagger UI到/api-docs路径
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

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

4.3 启动应用并访问文档

node app.js

打开浏览器访问http://localhost:3000/api-docs,即可看到交互式的Swagger文档,支持“Try it out”功能测试接口。

5. 自动化生成文档(可选,适用于代码优先的场景)

若已有后端代码(如Go、Java、Spring Boot),可使用工具从代码注释或注解自动生成OpenAPI规范,减少手动编写工作量。

5.1 Go语言(使用swag工具)

5.2 Java/Spring Boot(使用Springfox)

6. 最佳实践建议

0
看了该问题的人还看了