Featured image of post Java工程师 前后端开发协作 01 API文档

Java工程师 前后端开发协作 01 API文档

🌏Java工程师 测试 junit单元测试 🎯API文档是软件开发中不可或缺的一部分,它为开发者提供了使用和集成特定软件、库或API的必要指南、标准和示例。良好的API文档能够帮助团队更好地协作,提高开发效率。

概述

后端开发API文档的实现有多种方式 接下来记录使用SpringDoc的实现方式

添加依赖

首先,需要在项目的pom.xml文件中添加SpringDoc的依赖。如果你的Spring Boot版本是2.x,可以使用以下依赖(在项目的根目录添加):

<!-- API文档支持 20240501 -->
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.5</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

配置Swagger

@Configuration
public class OpenAPIConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
            .info(new Info()
                .title("My Application API")
                .version("1.0.0"));
    }
}

使用注解标记API

在控制器和实体类中使用Swagger注解,如@ApiOperation@ApiParam@ApiModel等,来增加API的文档描述。

@Slf4j
@RestController
@ApiModel(value = "帖子")
@RequestMapping("/post")
@RequiredArgsConstructor
public class PostController {
    ...
    @ApiOperation("帖子详情")
    @PostMapping("/detail")
    public Result<PostDetailVO> detail(@RequestBody Event req){
        log.info("C PostController M detail req = {}", req);
        return Result.success(ResultCodeEnum.SUCCESS, postBasicBizService.detail(req));
    }
    ...
}

启动应用并访问文档

启动Spring Boot应用,然后打开浏览器,访问以下URL来查看和测试你的API文档:

http://localhost:8080/swagger-ui/index.html

以JSON或YAML格式查看OpenAPI规范:

http://localhost:8080/swagger-ui/api-docs
http://localhost:8080/swagger-ui/api-docs.yaml
Licensed under CC BY-NC-SA 4.0