温馨提示×

Ubuntu下Swagger API文档怎么生成

小樊
51
2025-06-19 01:56:48
栏目: 智能运维

在Ubuntu下生成Swagger API文档,通常涉及以下几个步骤:

使用Spring Boot和Springfox

  1. 添加依赖
  • 在你的 pom.xml 文件中添加Springfox的依赖。例如:
<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>
  1. 配置Swagger
  • 创建一个配置类,使用 @EnableSwagger2 注解启用Swagger,并配置文档的基本信息和扫描包的路径。例如:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.yourproject"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Your API Title")
                .description("Your API Description")
                .contact(new Contact("Your Name", "https://www.example.com", "your.email@example.com"))
                .version("1.0")
                .build();
    }
}
  1. 编写API注解
  • 在你的Controller和方法上添加Swagger注解,例如 @ApiOperation@ApiParam 等。例如:
@Api(tags = ["Your API Tag"])
@RestController
@RequestMapping("/your-api")
public class YourController {
    @ApiOperation(value = "Your API Operation", notes = "Your API Notes")
    @GetMapping("/your-endpoint")
    public ResponseEntity<String> yourMethod(@ApiParam(value = "Your Param", required = false) @RequestParam(value = "param", required = false) String param) {
        // Your method implementation
    }
}
  1. 访问Swagger文档
  • 启动你的Spring Boot应用后,可以通过浏览器访问Swagger UI界面,通常是 http://localhost:8080/swagger-ui.html

使用Swagger Editor

  1. 安装Node.js和npm(如果尚未安装):
sudo apt update
sudo apt install -y nodejs npm
  1. 下载并安装Swagger Editor
  • 方法一:使用官网在线的Swagger Editor。
  • 方法二:下载Swagger Editor包并解压,然后在Swagger Editor目录下运行 http-server
  • 方法三:从Swagger官网下载并解压。
  1. 访问Swagger Editor
  • 打开浏览器,访问 http://localhost:8080(具体端口可能根据你的设置有所不同)。
  1. 导入或创建Swagger文档
  • 你可以导入现有的Swagger JSON或YAML文件,或者创建一个新的文档。
  1. 编辑和查看文档
  • 在Swagger Editor中直接编辑你的API文档,然后保存并查看。

以上步骤应该可以帮助你在Ubuntu系统下成功生成Swagger API文档。如果你使用的是其他框架或工具,步骤可能会有所不同。

0