使用Swagger 3注解编写API文档详解

发布于:2024-07-01 ⋅ 阅读:(16) ⋅ 点赞:(0)

在现代软件开发中,API文档的编写是至关重要的一环,它不仅能帮助开发者理解和正确使用API,还能提升团队协作效率。Swagger 3是一个流行的API文档规范,通过注解的方式可以清晰地定义API的各个方面。本文将深入探讨Swagger 3中常用的注解及其使用方法。

@OpenAPIDefinition 和 @Info

@OpenAPIDefinition 注解用于定义整个API文档的基本信息,通常应用于类或接口。

  • 属性:
    • info:指定 @Info 注解的对象,用于描述API文档的基本信息。

@Info 注解用于定义API文档的基本信息。

  • 属性:
    • title:API的标题。
    • description:API的描述。
    • version:API的版本号。
    • termsOfService:服务条款的URL。
    • contact:指定 @Contact 注解的对象,用于描述联系人信息。
    • license:指定 @License 注解的对象,用于描述许可证信息。
@OpenAPIDefinition(info = @Info(
    title = "用户管理API",
    description = "用于管理用户信息的API接口文档",
    version = "1.0.0",
    termsOfService = "https://example.com/terms",
    contact = @Contact(name = "API支持", url = "https://example.com/support", email = "support@example.com"),
    license = @License(name = "Apache 2.0", url = "http://www.apache.org/licenses/LICENSE-2.0.html")
))
@Tag

@Tag 注解用于给API分组,类似于为API文档添加标签,便于组织和查找。

  • 属性:
    • name:分组的名称。
    • description:分组的描述。
@Tag(name = "用户管理", description = "用于管理用户信息的API")
@Operation 和 @ApiResponse

@Operation 注解用于描述API的操作,通常应用于方法上。

  • 属性:
    • summary:操作的摘要信息。
    • description:操作的详细描述。
    • tags:指定 @Tag 注解的对象数组,用于将操作归类到特定的分组。
    • parameters:指定 @Parameter 注解的对象数组,用于描述操作的输入参数。
    • responses:指定 @ApiResponse 注解的对象数组,用于描述操作的响应结果。
    • requestBody:指定 @RequestBody 注解的对象,用于描述操作的请求体。
@Operation(summary = "根据ID获取用户信息", description = "根据用户ID查询用户的详细信息")
@ApiResponse(responseCode = "200", description = "成功获取用户信息")
@ApiResponse(responseCode = "404", description = "未找到对应用户")
@Parameter 和 @RequestBody

@Parameter 注解用于描述API操作的输入参数。

  • 属性:
    • name:参数的名称。
    • in:参数的位置,可以是 path、query、header、cookie 中的一种。
    • description:参数的描述。
    • required:参数是否必需,默认为 false。
    • schema:指定 @Schema 注解的对象,用于描述参数的数据类型。

@RequestBody 注解用于描述API操作的请求体。

  • 属性:
    • required:请求体是否必需,默认为 false。
    • content:指定 @Content 注解的对象数组,用于描述请求体的内容。
public ResponseEntity<User> getUserById(@PathVariable("id") Long id)
@Schema

@Schema 注解用于描述数据模型的属性,可用于方法、类、接口。

  • 属性:
    • title:数据模型的标题。
    • description:数据模型的描述。
    • type:数据模型的类型。
    • format:数据模型的格式。
@Schema(title = "用户信息", description = "描述用户的基本信息")
public class User {
    // User类的字段和方法
}

示例代码分析

下面是一个示例代码,演示了如何使用Swagger 3注解来编写API文档:

@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用于管理用户信息")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取用户信息", description = "根据用户ID查询用户的详细信息")
    @ApiResponse(responseCode = "200", description = "成功获取用户信息")
    @ApiResponse(responseCode = "404", description = "未找到对应用户")
    public ResponseEntity<User> getUserById(@PathVariable("id") Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    @ApiResponse(responseCode = "201", description = "成功创建用户")
    public ResponseEntity<User> createUser(@RequestBody CreateUserRequest request) {
        User user = userService.createUser(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新用户信息", description = "根据用户ID更新用户的信息")
    @ApiResponse(responseCode = "200", description = "成功更新用户信息")
    @ApiResponse(responseCode = "404", description = "未找到对应用户")
    public ResponseEntity<User> updateUser(@PathVariable("id") Long id, @RequestBody UpdateUserRequest request) {
        User user = userService.updateUser(id, request);
        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "根据用户ID删除用户")
    @ApiResponse(responseCode = "204", description = "成功删除用户")
    @ApiResponse(responseCode = "404", description = "未找到对应用户")
    public ResponseEntity<Void> deleteUser(@PathVariable("id") Long id) {
        boolean deleted = userService.deleteUser(id);
        if (deleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

通过上述示例,我们详细介绍了Swagger 3注解在API文档编写中的应用,包括基本信息定义、API分组、操作描述、参数定义、响应结果描述等方面。这些注解不仅使得API文档更加清晰和易读,同时也提升了开发团队的协作效率和代码的可维护性。