简体   繁体   English

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

[英]springdoc-openapi: How to add example of POST request?

Have the following method of Controller: 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) {
   }

I need to find a way how to show in Swagger example of PagingAndSorting object.我需要找到一种方法如何在PagingAndSorting object 的Swagger示例中显示。

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

You can use @ExampleObject annotation.您可以使用@ExampleObject 注释。

Note that you can also in the examples use the ref @ExampleObject(ref="..."), if you want to reference an sample existing object. Or ideally, fetch the examples from external configuration file and add them using OpenApiCustomiser, like it's done in this test:请注意,如果您想引用现有示例 object,您也可以在示例中使用 ref @ExampleObject(ref="...")。或者理想情况下,从外部配置文件中获取示例并使用 OpenApiCustomiser 添加它们,例如它在这个测试中完成:

Here is sample code using @ExampleObject:下面是使用@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 you are using the @RequestBody Spring annotation in the controller you need to differentiate the two, for example by using @io.swagger.v3.oas.annotations.parameters.RequestBody for the Swagger annotation.如果您在 controller 中使用@RequestBody Spring 注释,则需要区分两者,例如,通过对 Swagger 注释使用@io.swagger.v3.oas.annotations.parameters.RequestBody This prevents the null param problem mentioned in the comments below.这可以防止下面评论中提到的 null 参数问题。

@ExampleObject can be used for @RequestBody and @ApiResponse to add examples for springdoc openapi: https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/test/org/springdoc/api/app90/HelloController.java @ExampleObject可以用于@RequestBody和@ApiResponse为springdoc openapi添加例子: https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/test/ 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) {
    }

}

if you want to add OpenApiCustomiser in order to load your examples from resources you will need to start with something like this: https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/test/org/springdoc/api/app90/SpringDocTestApp.java如果你想添加 OpenApiCustomiser 以便从资源中加载你的示例,你需要从这样的东西开始: https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/测试/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());
            });
        };
    }

For header, cookie, query or path params you can use @Parameter: https://docs.swagger.io/swagger-core/v2.0.0-RC3/apidocs/io/swagger/v3/oas/annotations/Parameter.html对于 header、cookie、查询或路径参数,您可以使用@Parameter: https://docs.swagger.io/swagger-core/v2.0.0-RC3/apidocs/io/swagger/v3/oas/annotations/Parameter.html

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

eg例如

@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")})

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

If someone is still interested, this is how examples can be added programmatically to a specific endpoint:如果有人仍然感兴趣,这就是如何以编程方式将示例添加到特定端点:

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

If we are using spring boot, to add it to our Maven project, we need a dependency in the pom.xml file.如果我们使用 spring 启动,要将它添加到我们的 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();                                           
    }
}

Configuration Without Spring Boot没有 Spring 引导的配置

@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: To verify that Springfox is working, you can visit the following URL in your browser: http://localhost:8080/our-app-root/api/v2/api-docs验证:验证Springfox是否正常,可以在浏览器访问如下URL:http://localhost:8080/our-app-root/api/v2/api-docs

To use Swagger UI, one additional Maven dependency is required:要使用 Swagger UI,需要一个额外的 Maven 依赖项:

<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您可以通过访问 http://localhost:8080/our-app-root/swagger-ui.html 在浏览器中对其进行测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为 springdoc-openapi 端点调用添加 Header 授权 - How to add Header with Authorization for springdoc-openapi endpoint calls springdoc-openapi 不同的例子 - springdoc-openapi different examples 如何使用springdoc-openapi以相反的顺序对端点进行排序 - How to sort endpoint in reverse order using springdoc-openapi Springdoc-OpenAPI 带路径参数和命令 object - Springdoc-OpenAPI with path parameters and command object Springdoc Openapi - 添加响应示例值 - Springdoc Openapi - Add Response Example Value Java springdoc-openapi 在 Swagger UI 示例值中显示带有附加日期/时间字段的 LocalDateTime 字段 - Java springdoc-openapi show LocalDateTime field with additional date/time fields in Swagger UI Example Value springdoc-openapi、swagger UI 中的 XML 示例 - XML examples in springdoc-openapi, swagger UI springdoc-openapi 如何在不更改 toString 的情况下使用 @JsonValue 枚举格式? - How can have springdoc-openapi use the @JsonValue enum format without changing toString? 如何使用带有 Lombok getter 的 springdoc-openapi 将 @JsonValue 用于 Swagger 枚举值 - How can @JsonValue be used for Swagger enum values using springdoc-openapi with a Lombok getter 如何使用 springdoc-openapi 将 Open API 3 与 Spring 项目(不是 Spring Boot)集成 - How to Integrate Open API 3 with Spring project (not Spring Boot) using springdoc-openapi
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM