
本文介绍如何在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。 具体的集成方法请参考这些库的官方文档。
以上就是linux上swagger文档如何生成的详细内容,更多请关注代码网其它相关文章!
发表评论