springdoc-openapi:如何添加POST请求示例?

问题描述

具有以下Controller方法

    @ApiResponses(value = {@ApiResponse(responseCode = "200")})
    @GetMapping(value = API_URI_PREFIX + PRODUCTS_URI,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public Flux<Product> getProducts(@Valid @NotNull PagingAndSorting pagingAndSorting) {
   }

我需要找到一种方法显示Swagger对象的PagingAndSorting示例。

我正在使用springdoc-api v1.4.3。

解决方法

您可以使用@ExampleObject批注。

请注意,如果要引用示例现有对象,则还可以在示例中使用ref @ExampleObject(ref =“ ...”)。或者理想情况下,可以从外部配置文件中获取示例,然后使用OpenApiCustomiser进行添加,就像在此测试中一样:

以下是使用@ExampleObject的示例代码:

@PostMapping("/test/{id}")
public void testme(@PathVariable("id") String id,@RequestBody(content = @Content(examples = {
        @ExampleObject(
                name = "Person sample",summary = "person example",value =
                        "{\"email\": test@gmail.Com,"
                                + "\"firstName\": \"josh\","
                                + "\"lastName\": \"spring...\""
                                + "}")
})) PersonDTO personDTO) { }
,
If we are using spring boot:
Add it to our Maven project,we need a dependency in the pom.xml file.
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

@Configuration
@EnableSwagger2
public class SpringConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

**Configuration Without Spring Boot**

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");
 
    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

**Verify:**
verify that Springfox is working,you can visit the following URL in your browser:
http://localhost:8080/our-app-root/api/v2/api-docs

To use Swagger UI,one additional Maven dependency is required:
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

you can test it in your browser by visiting http://localhost:8080/our-app-root/swagger-ui.html