温馨提示×

Linux Swagger文档如何生成

小樊
44
2026-07-22 03:46:54
栏目: 智能运维

在 Linux 环境下生成 Swagger 文档,常见做法取决于你使用的后端语言/框架。下面按主流场景给你一个通用 + 示例说明,基本都能在 Linux 上直接操作。


一、Swagger 文档生成的通用思路

无论是哪种语言,核心流程通常是:

  1. 在代码中写接口 + Swagger 注解
  2. 启动服务
  3. 自动生成 Swagger JSON / YAML
  4. 用 Swagger UI 展示

二、常见语言/框架示例

✅ 1. Java + Spring Boot(最常见)

① 添加依赖(Maven)

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

② 启动项目

mvn spring-boot:run

③ 访问 Swagger 文档

  • Swagger UI
    http://localhost:8080/swagger-ui.html
    
  • OpenAPI JSON
    http://localhost:8080/v3/api-docs
    

无需手动生成,Spring Boot 自动生成


✅ 2. Go + Swag(非常常见)

① 安装 swag

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

② 在代码中写注释

// @Summary 获取用户
// @Description 获取用户信息
// @Tags user
// @Produce json
// @Success 200 {string} string "ok"
// @Router /user [get]

③ 生成文档

swag init

生成文件:

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

④ 启动项目并访问

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

✅ 3. Python + FastAPI(最简单)

FastAPI 自动生成 Swagger

pip install fastapi uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

启动:

uvicorn main:app --host 0.0.0.0 --port 8000

访问:

http://localhost:8000/docs

无需任何额外配置


✅ 4. Node.js + Express

安装

npm install swagger-ui-express swagger-jsdoc

示例

const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const options = {
  definition: {
    openapi: '3.0.0',
    info: { title: 'API', version: '1.0.0' }
  },
  apis: ['./index.js']
};

const swaggerSpec = swaggerJsdoc(options);

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

访问:

http://localhost:3000/api-docs

三、从已有接口“反向生成”Swagger(无注解)

如果你已有接口但没写注解:

方法 1:抓接口流量生成

swagger-inline api.log

方法 2:使用工具

  • Swagger Editor
  • Postman → Export OpenAPI
  • Charles / Fiddler + 转换工具

四、Linux 下常用生成命令总结

场景 命令
Go swag init
Java 自动生成
Python 自动生成
Node 代码生成
导出 JSON curl http://localhost/v3/api-docs > swagger.json

五、我可以帮你更具体

你可以直接告诉我:

  • 用的什么语言?
  • 框架是什么?
  • 想生成 JSON / YAML / HTML?
  • 用于接口测试还是前端对接?

我可以给你一步一步的 Linux 实操命令

0