1、概览 本文将带你了解 Swagger 中 @Operation 和 @ApiResponse 注解的主要区别和应用场景。
2、用 Swagger 生成文档 Swagger 是一套围绕 OpenAPI 规范构建的开源工具,用于描述整个 API,如暴露的端点、操作、参数、验证方法等。
Swagger 提供了 @Operation 和 @ApiResponse 注解,用于描述 REST API,以及 REST API 的响应。
定义一个示例 Controller:
@RestController @RequestMapping("/customers") class CustomerController { private final CustomerService customerService; public CustomerController(CustomerService customerService) { this.customerService = customerService; } @GetMapping("/{id}") public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) { return ResponseEntity.ok(customerService.getById(id)); } } 3、@Operation @Operation 注解用于描述单个操作。
@Operation(summary = "Gets customer by ID", description= "Customer must exist") @GetMapping("/{id}") public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) { return ResponseEntity.
1、概览 本文介绍了如何在 API 规范中,为同一个响应定义多个不同的对象,以及如何使用该规范生成 Java 代码和 Swagger 文档。
2、问题陈述 定义两个对象(object)。
Car 对象的属性是 owner 和 plate,两者都是 String。 Bike 对象的属性是 owner 和 speed,speed 是一个 Integer。 它们在 OpenAPI 中的描述如下:
Car: type: object properties: owner: type: string plate: type: string Bike: type: object properties: owner: type: string speed: type: integer 我们想描述一个 /vehicle 端点,它将接受 GET 请求,并能返回一个 Car 或一个 Bike。
类似于如下描述:
paths: /vehicle: get: responses: '200': # 返回 Car 或 Bike 接下来介绍在 OpenAPI 2 和 3 规范中的不同实现方式。
1、概览 Springfox 和 SpringDoc 这两个工具简化了 Swagger API 文档的生成和维护。
在本教程中,我们将了解如何在 Spring Boot 应用中更改 Swagger-UI URL 前缀。
2、使用 Springdoc 时更改 Swagger UI URL 前缀 首先,我们可以看看 如何使用 OpenAPI 3.0 生成 REST API 文档。
根据上述教程,我们需要添加如下 SpringDoc 的依赖:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.0.2</version> </dependency> swagger-ui 的默认 URL 是 http://localhost:8080/swagger-ui.html。
比方说,我们要增加 /myproject 前缀,接下来让我们看看自定义 swagger-UI URL 的两种方法。
2.1、application.properties 我们可以在 application.properties 文件中添加以下属性来修改 swagger-UI URL:
springdoc.swagger-ui.disable-swagger-default-url=true springdoc.swagger-ui.path=/myproject 2.2、配置类 我们也可以通过配置类来实现:
@Component public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> { @Override public void onApplicationEvent(final ApplicationPreparedEvent event) { ConfigurableEnvironment environment = event.
1、概览 在本教程中,我们将演示如何使用 Swagger 注解使我们的文档更具描述性。我们会学习如何为 API 的不同部分(如方法、参数、响应等)添加描述,以及如何添加请求/响应示例。
2、项目设置 我们将创建一个简单的 Product API,提供创建和获取 product 的方法。
要从头开始创建 REST API,我们可以按照 Spring 文档中的教程 使用 Spring Boot 创建 RESTful Web 服务。
下一步是为项目设置依赖和配置。我们可以按照 本文 中的步骤使用 Spring REST API 设置 Swagger 2
3、创建 API 创建 Product API 并检查生成的文档。
3.1、Model 定义 Product 类:
public class Product implements Serializable { private long id; private String name; private String price; // 省略 get/set 构造函数 } 3.2、Controller 定义两个 API 方法:
@RestController @Tag(name = "Products API") public class ProductController { @PostMapping("/products") public ResponseEntity<Void> createProduct(@RequestBody Product product) { //creation logic return new ResponseEntity<>(HttpStatus.