温馨提示×

怎样生成linux swagger文档

小樊
50
2026-09-03 12:57:07
栏目: 智能运维

在 Linux 环境下生成 Swagger 文档(现在多指 OpenAPI 文档),常见做法取决于你使用的后端语言/框架。下面按最主流场景给你一个清晰指南。


一、常见生成方式总览

场景 方式
Spring Boot (Java) springdoc / swagger-ui
Go swaggo
Python (FastAPI) 自动生成
Python (Flask) flasgger / apispec
手动编写 YAML / JSON

二、Spring Boot(最常见)

1️⃣ 引入依赖(Maven)

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.3.0</version>
</dependency>

2️⃣ 启动项目

mvn spring-boot:run

3️⃣ 访问 Swagger 文档

http://localhost:8080/swagger-ui.html

4️⃣ 导出 OpenAPI JSON

curl http://localhost:8080/v3/api-docs > openapi.json

三、Go(swaggo)

1️⃣ 安装 swag

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

2️⃣ 写注释

// @title My API
// @version 1.0
// @BasePath /api

3️⃣ 生成文档

swag init

生成目录:

docs/
 ├── docs.go
 ├── swagger.json
 └── swagger.yaml

4️⃣ 访问

http://localhost:8080/swagger/index.html

四、Python FastAPI(最简)

from fastapi import FastAPI

app = FastAPI()

@app.get("/items")
def read_items():
    return [{"id": 1}]

启动:

uvicorn main:app --reload

文档自动生成:

http://localhost:8000/docs

导出:

http://localhost:8000/openapi.json

五、手动编写 Swagger(通用)

swagger.yaml 示例

openapi: 3.0.0
info:
  title: Demo API
  version: 1.0.0
paths:
  /ping:
    get:
      responses:
        '200':
          description: OK

生成 HTML:

npm i -g swagger-cli
swagger-cli validate swagger.yaml

或使用:

npx redoc-cli build swagger.yaml

六、Linux 常用辅助工具

# 格式化 JSON
jq . openapi.json

# 启动静态文档
python3 -m http.server 8000

七、你可以告诉我

为了给你最准确方案,你可以补充:

  • 使用的语言(Java / Go / Python / Node)
  • 是否已有项目
  • 想要 UI 页面 还是 JSON/YAML 文件

我可以直接给你可复制的命令。

0 踩