溫馨提示×

Ubuntu下Swagger文檔怎么生成

小樊
61
2025-05-31 19:47:50
欄目: 智能運維

在Ubuntu系統下生成Swagger API文檔,通常需要根據你所使用的編程語言和框架來選擇相應的工具和方法。以下是幾種常見的方法:

使用Swagger Editor

  1. 安裝Node.js和npm
sudo apt update
sudo apt install nodejs npm
  1. 下載并安裝Swagger Editor

    • 方法一:使用官網在線的Swagger Editor。
    • 方法二:下載Swagger Editor包并解壓,然后在Swagger Editor目錄下運行 http-server。
  2. 訪問Swagger Editor: 打開瀏覽器,訪問 http://localhost:8080(具體端口可能根據你的設置有所不同)。

  3. 導入或創建Swagger文檔: 你可以導入現有的Swagger JSON或YAML文件,或者創建一個新的文檔。

  4. 編輯和查看文檔: 在Swagger Editor中直接編輯你的API文檔,然后保存并查看。

使用編程方式生成Swagger文檔

使用Go語言和swag工具

  1. 安裝swag工具
go install github.com/swaggo/swag/cmd/swag@latest
  1. 初始化swag: 在項目的根目錄下運行以下命令,這將生成一個 docs.go 文件,其中包含了Swagger文檔的代碼。
swag init
  1. 在代碼中添加Swagger注釋: 在你的Go代碼中,使用特定的注釋來描述API的端點、請求參數、響應格式等信息。
// @Summary 獲取用戶信息
// @Description 獲取用戶信息
// @Tags Users
// @Accept json
// @Produce json
// @Param id path int true "用戶ID"
// @Success 200 {object} User
// @Router /users/{id} [get]
  1. 生成文檔: 再次運行 swag init 命令,swag工具會根據你的注釋生成相應的Swagger文檔。

使用Spring Boot和Springfox

  1. 添加依賴: 在你的 pom.xml 文件中添加Springfox的依賴。
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
  1. 配置Swagger: 創建一個配置類,使用 @EnableSwagger2 注解啟用Swagger,并配置文檔的基本信息和掃描包的路徑。
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.weijishu.server.api.rest"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Weijishu Swagger API Document")
                .description("Weijishu Swagger Description...")
                .contact(new Contact("Weijishu", "https://www.weijisu.cn/", "mail@weijishu.cn"))
                .version("0.1")
                .build();
    }
}
  1. 使用Swagger注解: 在你的控制器中使用Swagger注解來標記API。
@Api(tags ["SwaggerDemo"])
@RestController
@RequestMapping("/weijishu")
public class WeijishuSwagger2Controller {
    @ApiOperation(value = "方法說明", notes = "通過A")
    @PostMapping("/add")
    public ResponseEntity<String> add(@RequestBody String requestBody) {
        // 你的業務邏輯
        return ResponseEntity.ok("Success");
    }
}
  1. 訪問Swagger文檔: 啟動你的Spring Boot應用后,可以通過 http://localhost:8080/swagger-ui.html 訪問生成的Swagger文檔。

希望這些信息能幫助你在Ubuntu系統下成功生成Swagger API文檔。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女