本文介紹如何在Linux系統(tǒng)上生成Swagger文檔,主要針對(duì)基于spring Boot的Java項(xiàng)目。其他語言(如Python或Node.JS)的實(shí)現(xiàn)方法略有不同。
一、添加Swagger依賴 (maven項(xiàng)目)
在pom.xml文件中添加以下依賴項(xiàng),版本號(hào)請(qǐng)根據(jù)您的spring boot版本調(diào)整:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
二、Swagger配置 (Spring Boot)
創(chuàng)建一個(gè)配置類,例如SwaggerConfig.java,并添加如下代碼:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.yourproject")) // 請(qǐng)?zhí)鎿Q為您的Controller包路徑 .paths(PathSelectors.any()) .build(); } }
請(qǐng)將”com.example.yourproject”替換為您的項(xiàng)目中Controller所在的包路徑。
三、啟動(dòng)項(xiàng)目并訪問Swagger UI
啟動(dòng)Spring Boot應(yīng)用后,通常可以通過http://localhost:8080/swagger-ui.html訪問Swagger UI界面。
四、生成Swagger文檔
在Swagger UI界面中,您可以:
- 點(diǎn)擊“Authorize”(如有需要)進(jìn)行授權(quán)。
- 點(diǎn)擊“Download Swagger JSON”下載json格式的API文檔。
- 點(diǎn)擊“Download Swagger YAML”下載YAML格式的API文檔。
五、使用Swagger Editor (可選)
Swagger Editor是一個(gè)可視化編輯器,方便編寫和管理OpenAPI規(guī)范。您可以使用docker部署并通過內(nèi)網(wǎng)穿透工具遠(yuǎn)程訪問。
其他語言框架的Swagger集成:
對(duì)于Python (flask) 項(xiàng)目,可以考慮使用flask-swag或flasgger庫;Node.js項(xiàng)目可以使用swagger-jsdoc和swagger-ui-express。 具體的集成方法請(qǐng)參考這些庫的官方文檔。