温馨提示×

怎样写linux swagger文档

小樊
36
2026-09-15 18:59:28
栏目: 智能运维

在 Linux 环境下编写 Swagger(OpenAPI)文档,通常有三种常见方式:

  1. 手写 OpenAPI YAML / JSON 文件
  2. 在代码中通过注解自动生成(如 Springfox、swaggo、FastAPI 等)
  3. 使用 Swagger Editor / CLI 工具辅助编写

下面按「从零开始」的思路说明。


一、准备环境(Linux)

1. 安装基础工具

# 安装 node(用于 swagger-cli / editor)
sudo apt update
sudo apt install -y nodejs npm

# 安装 swagger-cli
sudo npm install -g swagger-cli

# 可选:安装 yaml 工具
sudo apt install -y yamllint

2. 目录结构示例

mkdir swagger-demo && cd swagger-demo
touch swagger.yaml

二、手写 Swagger 文档(OpenAPI 3.0)

示例:swagger.yaml

openapi: 3.0.3
info:
  title: User API
  version: 1.0.0
  description: Linux 环境下编写的 Swagger 文档示例

servers:
  - url: http://localhost:8080/api

paths:
  /users:
    get:
      summary: 获取用户列表
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'

  /users/{id}:
    get:
      summary: 根据ID获取用户
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string

三、校验 Swagger 文档

swagger-cli validate swagger.yaml

输出:

swagger.yaml is valid

四、本地预览 Swagger 文档

方式 1:Swagger Editor

docker run -d -p 8081:8080 swaggerapi/swagger-editor

浏览器访问:

http://localhost:8081

方式 2:Swagger UI

docker run -d -p 8080:8080 \
  -e SWAGGER_JSON=/swagger.yaml \
  -v $PWD/swagger.yaml:/swagger.yaml \
  swaggerapi/swagger-ui

五、代码自动生成(常见语言)

1. Go(swaggo)

go install github.com/swaggo/swag/cmd/swag@latest
swag init

2. Java(Spring Boot)

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
</dependency>

3. Python(FastAPI)

from fastapi import FastAPI
app = FastAPI()

@app.get("/users")
def read_users():
    return []

自动生成:

http://localhost:8000/docs

六、推荐实践

✅ 使用 YAML 而非 JSON(更易维护)
✅ 将 Swagger 文件纳入 Git 管理
✅ CI 中加 swagger-cli validate
✅ 接口变更先改文档,再改代码


如果你告诉我:

  • 使用的 语言 / 框架
  • 是否要 自动生成

我可以给你更具体的示例。

0