Hello! 欢迎来到小浪云!


Linux上Swagger文档如何生成


avatar
小浪云 2025-02-25 77

Linux上Swagger文档如何生成

本文介绍如何在Linux系统上生成Swagger文档,主要针对基于spring Boot的Java项目。其他语言(如Python或Node.JS)的实现方法略有不同。

一、添加Swagger依赖 (maven项目)

在pom.xml文件中添加以下依赖项,版本号请根据您的spring boot版本调整:

<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)

创建一个配置类,例如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")) // 请替换为您的Controller包路径                 .paths(PathSelectors.any())                 .build();     } }

请将”com.example.yourproject”替换为您的项目中Controller所在的包路径。

三、启动项目并访问Swagger UI

启动Spring Boot应用后,通常可以通过http://localhost:8080/swagger-ui.html访问Swagger UI界面。

四、生成Swagger文档

在Swagger UI界面中,您可以:

  • 点击“Authorize”(如有需要)进行授权。
  • 点击“Download Swagger JSON”下载json格式的API文档。
  • 点击“Download Swagger YAML”下载YAML格式的API文档。

五、使用Swagger Editor (可选)

Swagger Editor是一个可视化编辑器,方便编写和管理OpenAPI规范。您可以使用docker部署并通过内网穿透工具远程访问。

其他语言框架的Swagger集成:

对于Python (flask) 项目,可以考虑使用flask-swag或flasgger库;Node.js项目可以使用swagger-jsdoc和swagger-ui-express。 具体的集成方法请参考这些库的官方文档。

相关阅读