ubuntu

Ubuntu下Swagger文档怎么生成

小樊
45
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
看了该问题的人还看了