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

huangapple go评论76阅读模式
英文:

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

问题

以下是翻译好的内容:

有以下 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 版本 1.4.3。

英文:

Have the following method of Controller:

    @ApiResponses(value = {@ApiResponse(responseCode = &quot;200&quot;)})
    @GetMapping(value = API_URI_PREFIX + PRODUCTS_URI, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.OK)
    public Flux&lt;Product&gt; getProducts(@Valid @NotNull PagingAndSorting pagingAndSorting) {
   }

I need to find a way how to show in Swagger example of PagingAndSorting object.

I am using springdoc-api v1.4.3.

答案1

得分: 14

你可以使用 @ExampleObject 注解。

请注意,你也可以在示例中使用 @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) { }

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

英文:

You can use @ExampleObject annotation.

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:

Here is sample code using @ExampleObject:

@PostMapping(&quot;/test/{id}&quot;)
public void testme(@PathVariable(&quot;id&quot;) String id, @RequestBody(content = @Content(examples = {
		@ExampleObject(
				name = &quot;Person sample&quot;,
				summary = &quot;person example&quot;,
				value =
						&quot;{\&quot;email\&quot;: test@gmail.Com,&quot;
								+ &quot;\&quot;firstName\&quot;: \&quot;josh\&quot;,&quot;
								+ &quot;\&quot;lastName\&quot;: \&quot;spring...\&quot;&quot;
								+ &quot;}&quot;)
})) 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. This prevents the null param problem mentioned in the comments below.

答案2

得分: 4

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

}

如果您想要添加 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());
		});
	};
}

对于 headercookiequery 或者 path 参数您可以使用 @Parameterhttps://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/
英文:

@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

@RestController
public class HelloController {
/**
* Test 1.
*
* @param hello the hello
*/
@GetMapping(&quot;/test&quot;)
@ApiResponses(value = { @ApiResponse(description = &quot;successful operation&quot;,content = { @Content(examples = @ExampleObject(name = &quot;500&quot;, ref = &quot;#/components/examples/http500Example&quot;), mediaType = &quot;application/json&quot;, schema = @Schema(implementation = User.class)), @Content(mediaType = &quot;application/xml&quot;, schema = @Schema(implementation = User.class)) }) })
public void test1(String hello) {
}
/**
* Test 2.
*
* @param hello the hello
*/
@PostMapping(&quot;/test2&quot;)
@RequestBody(
description = &quot;Details of the Item to be created&quot;,
required = true,
content = @Content(
schema = @Schema(implementation = User.class),
mediaType = MediaType.APPLICATION_JSON_VALUE,
examples = {
@ExampleObject(
name = &quot;An example request with the minimum required fields to create.&quot;,
value = &quot;min&quot;,
summary = &quot;Minimal request&quot;),
@ExampleObject(
name = &quot;An example request with all fields provided with example values.&quot;,
value = &quot;full&quot;,
summary = &quot;Full request&quot;) }))
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

@Bean
public OpenApiCustomiser openApiCustomiser(Collection&lt;Entry&lt;String, Example&gt;&gt; examples) {
return openAPI -&gt; {
examples.forEach(example -&gt; {
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

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

e.g.

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

Another way is to add @Schema(type = "string", example = "min") on your DTO. e.g. : https://www.dariawan.com/tutorials/spring/documenting-spring-boot-rest-api-springdoc-openapi-3/

答案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));
}
英文:

If someone is still interested, this is how examples can be added programmatically to a specific endpoint:

@Bean
public OpenApiCustomiser mockExamples() {
return openAPI -&gt;
getRequestBodyContent(openAPI, PXL_MOCK_PATH + &quot;/transactions&quot;, &quot;application/json&quot;).ifPresent(request -&gt;
Arrays.stream(PxlMockCase.values()).forEach(mockCase -&gt; {
request.addExamples(
mockCase.name(),
new Example()
.description(mockCase.getDescription())
.value(TransactionCodeRequest.builder().accountId(mockCase.getAccountId()).workflowId(15).build())
);
}));
}
private Optional&lt;MediaType&gt; getRequestBodyContent(OpenAPI api, String path, String bodyType) {
return Optional.ofNullable(api.getPaths())
.map(paths -&gt; paths.get(path))
.map(PathItem::getPost)
.map(Operation::getRequestBody)
.map(RequestBody::getContent)
.map(content -&gt; content.get(bodyType));
}

答案4

得分: -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是否工作,您可以在浏览器中访问以下网址:
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 在浏览器中进行测试。
英文:

If we are using spring boot, to add it to our Maven project, we need a dependency in the pom.xml file.

&lt;dependency&gt;
&lt;groupId&gt;io.springfox&lt;/groupId&gt;
&lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
&lt;version&gt;2.9.2&lt;/version&gt;
&lt;/dependency&gt;

<!-- -->

@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(&quot;swagger-ui.html&quot;)
.addResourceLocations(&quot;classpath:/META-INF/resources/&quot;);
registry.addResourceHandler(&quot;/webjars/**&quot;)
.addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;);
}

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

To use Swagger UI, one additional Maven dependency is required:

&lt;dependency&gt;
&lt;groupId&gt;io.springfox&lt;/groupId&gt;
&lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;
&lt;version&gt;2.9.2&lt;/version&gt;
&lt;/dependency&gt;

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

huangapple
  • 本文由 发表于 2020年8月18日 17:30:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63465763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定