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

问题描述 投票:0回答:4

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.

java swagger swagger-ui springdoc springdoc-openapi-ui
4个回答
16
投票

您可以使用@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\": [email protected],"
                            + "\"firstName\": \"josh\","
                            + "\"lastName\": \"spring...\""
                            + "}"
                )
})) PersonDTO personDTO) { }

如果您在控制器中使用

@RequestBody
Spring 注释,则需要区分两者,例如使用
@io.swagger.v3.oas.annotations.parameters.RequestBody
作为 Swagger 注释。这可以防止下面评论中提到的空参数问题。


4
投票

@ExampleObject 可用于 @RequestBody 和 @ApiResponse 来添加 springdoc openapi 的示例: https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/测试/org/springdoc/api/app90/HelloController.java

@RestController
public class HelloController {

    /**
     * Test 1.
     *
     * @param hello the hello
     */
    @GetMapping("/test")
    @ApiResponses(value = { @ApiResponse(description = "successful operation",content = { @Content(examples = @ExampleObject(name = "500", ref = "#/components/examples/http500Example"), mediaType = "application/json", schema = @Schema(implementation = User.class)), @Content(mediaType = "application/xml", schema = @Schema(implementation = User.class)) }) })
    public void test1(String hello) {
    }

    /**
     * Test 2.
     *
     * @param hello the hello
     */
    @PostMapping("/test2")
    @RequestBody(
            description = "Details of the Item to be created",
            required = true,
            content = @Content(
                    schema = @Schema(implementation = User.class),
                    mediaType = MediaType.APPLICATION_JSON_VALUE,
                    examples = {
                            @ExampleObject(
                                    name = "An example request with the minimum required fields to create.",
                                    value = "min",
                                    summary = "Minimal request"),
                            @ExampleObject(
                                    name = "An example request with all fields provided with example values.",
                                    value = "full",
                                    summary = "Full request") }))
    public void test2(String hello) {
    }

}

如果您想添加 OpenApiCustomiser 以便从资源加载示例,您将需要从以下内容开始: https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/test/org/springdoc/api/app90/SpringDocTestApp.java

@Bean
    public OpenApiCustomiser openApiCustomiser(Collection<Entry<String, Example>> examples) {
        return openAPI -> {
            examples.forEach(example -> {
                openAPI.getComponents().addExamples(example.getKey(), example.getValue());
            });
        };
    }

对于标头、cookie、查询或路径参数,您可以使用@Parameter:https://docs.swagger.io/swagger-core/v2.0.0-RC3/apidocs/io/swagger/v3/oas/annotations/Parameter .html

带有 ParameterIn 枚举:https://docs.swagger.io/swagger-core/v2.0.0/apidocs/io/swagger/v3/oas/annotations/enums/ParameterIn.html

例如

@Parameter(in = ParameterIn.PATH, name = "id", description="Id of the entity to be update. Cannot be empty.",
        required=true, examples = {@ExampleObject(name = "id value example", value = "6317260b825729661f71eaec")})

另一种方法是在 DTO 上添加 @Schema(type = "string", example = "min")。例如:https://www.dariawan.com/tutorials/spring/documenting-spring-boot-rest-api-springdoc-openapi-3/


0
投票

如果有人仍然感兴趣,可以通过以下方式以编程方式将示例添加到特定端点:

@Bean
 public OpenApiCustomiser mockExamples() {
    return openAPI ->
        getRequestBodyContent(openAPI, PXL_MOCK_PATH + "/transactions", "application/json").ifPresent(request ->
            Arrays.stream(PxlMockCase.values()).forEach(mockCase -> {
                request.addExamples(
                    mockCase.name(),
                    new Example()
                        .description(mockCase.getDescription())
                        .value(TransactionCodeRequest.builder().accountId(mockCase.getAccountId()).workflowId(15).build())
                );
            }));
}

private Optional<MediaType> getRequestBodyContent(OpenAPI api, String path, String bodyType) {
    return Optional.ofNullable(api.getPaths())
        .map(paths -> paths.get(path))
        .map(PathItem::getPost)
        .map(Operation::getRequestBody)
        .map(RequestBody::getContent)
        .map(content -> content.get(bodyType));
}

-4
投票

如果我们使用 Spring Boot,要将其添加到我们的 Maven 项目中,我们需要在 pom.xml 文件中添加依赖项。

<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();                                           
    }
}

不使用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/");
}

验证: 要验证 Springfox 是否正常工作,您可以在浏览器中访问以下 URL: http://localhost:8080/our-app-root/api/v2/api-docs

要使用 Swagger UI,需要一个额外的 Maven 依赖项:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

您可以通过访问 http://localhost:8080/our-app-root/swagger-ui.html 在浏览器中进行测试

© www.soinside.com 2019 - 2024. All rights reserved.