在Ubuntu中生成與查看Swagger文檔的常見方法
Swagger是一套用于描述、構建和文檔化RESTful API的工具集,支持通過代碼注解自動生成文檔,并提供交互式界面測試API。以下是在Ubuntu系統中生成與查看Swagger文檔的具體步驟,涵蓋不同工具和場景:
在生成Swagger文檔前,需確保Ubuntu系統已安裝Node.js和npm(Node.js包管理器),這是使用Swagger Editor、Swagger UI等工具的基礎:
sudo apt update
sudo apt install -y nodejs npm
Swagger Editor是一個開源的在線/離線工具,支持直接編輯Swagger YAML/JSON文件并實時預覽文檔效果。
sudo npm install -g swagger-editor-cli
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
tar -xvf v3.16.1.tar.gz
cd swagger-editor-3.16.1
swagger-editor
http-server
,再啟動:sudo npm install -g http-server
http-server -p 8080
http://localhost:8080
,進入Swagger Editor界面。swagger.yaml
或swagger.json
文件。Swagger UI是一個可視化工具,可將Swagger YAML/JSON文件渲染為交互式API文檔,支持在線測試接口。
sudo npm install -g swagger-ui-express
創建一個簡單的Node.js服務器,用于托管Swagger文檔:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./path/to/your/swagger.json'); // 替換為你的文檔路徑
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); // 掛載Swagger UI到/api-docs路徑
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Swagger UI is running at http://localhost:${PORT}/api-docs`);
});
node your-server-file.js
http://localhost:3000/api-docs
,即可看到Swagger UI界面,包含API的所有端點、參數、響應示例等信息。若項目使用Go語言開發,可使用swag
工具根據代碼中的注釋自動生成Swagger文檔。
在終端運行以下命令安裝:
go install github.com/swaggo/swag/cmd/swag@latest
在Go代碼的關鍵位置添加注釋,描述API信息。例如:
package main
import (
"net/http"
)
// @Summary 獲取用戶信息
// @Description 根據用戶ID返回用戶詳情
// @Tags Users
// @Accept json
// @Produce json
// @Param id path int true "用戶ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
func getUserByID(w http.ResponseWriter, r *http.Request) {
// 業務邏輯
}
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
docs
目錄(包含swagger.json
、swagger.yaml
和docs.go
):swag init
若項目使用Maven或Gradle構建,可將Swagger Codegen集成到構建過程中,自動生成文檔。
在pom.xml
中添加OpenAPI Generator插件:
<build>
<plugins>
<plugin>
<groupId>org.openapitools</groupId>
<artifactId>openapi-generator-maven-plugin</artifactId>
<version>5.2.1</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<inputSpec>${project.basedir}/src/main/resources/swagger.yaml</inputSpec>
<generatorName>html2</generatorName>
<output>${project.build.directory}/generated-docs</output>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
運行mvn generate-sources
即可生成HTML文檔。
在build.gradle
中添加OpenAPI Generator任務:
plugins {
id 'org.openapitools.codegen' version '5.2.1'
}
openApiGenerate {
inputSpec = file("src/main/resources/swagger.yaml").toString()
generatorName = 'html2'
outputDir = file("build/generated-docs")
}
運行gradle openApiGenerate
生成文檔。
/v2/api-docs
或/swagger.json
)可訪問。@CrossOrigin
注解)。springdoc-openapi
,Go推薦swag
)。