如何提供给别人 Java API 接口文档

在开发 Java 项目时,提供清晰的 API 接口文档对于其他开发人员使用我们的代码非常重要。下面我们将介绍如何使用 Swagger 工具来生成和发布 Java API 接口文档。

1. 引入 Swagger 依赖

首先,在 Maven 项目中添加 Swagger 依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

2. 编写接口文档注解

在 Controller 层的接口方法上添加 Swagger 相关的注解,示例代码如下:

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Tag(name = "User API", description = "Operations for managing users")
public class UserController {

    @Operation(summary = "Get user by ID")
    @ApiResponse(responseCode = "200", description = "User found", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class)))
    @GetMapping("/users/{id}")
    public User getUserById(@Parameter(description = "User ID") Long id) {
        // Your code here
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

3. 配置 Swagger

在 Spring Boot 项目中创建一个配置类,启用 Swagger 并设置扫描的包路径:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
@EnableOpenApi
@EnableWebMvc
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

4. 访问 Swagger UI

启动应用程序后,访问 http://localhost:8080/swagger-ui/ 即可查看生成的 API 文档并测试接口功能。

5. 旅行图

journey
    title API 接口文档之旅

    section 提供清晰的接口文档
        开始
            开发人员引入 Swagger 依赖
            编写接口文档注解
            配置 Swagger
            启动应用程序
        进行中
            访问 Swagger UI
        结束
            完成 API 接口文档的生成和发布

6. 序列图

Spring Boot Swagger 开发人员 Spring Boot Swagger 开发人员 添加 Swagger 依赖 编写接口文档注解 配置 Swagger 启动应用程序 访问 Swagger UI

结论

通过以上步骤,我们可以使用 Swagger 工具轻松地为 Java 项目生成并发布清晰的 API 接口文档,帮助其他开发人员更好地了解和使用我们的接口。让我们的代码变得更加开放和易用。