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

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

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

问题

以下是翻译好的内容:

有以下 Controller 的方法:

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

我需要找到一种方法,如何在 Swagger 中展示 PagingAndSorting 对象的示例。

我正在使用 springdoc-api 版本 1.4.3。

英文:

Have the following method of Controller:

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

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 的示例代码:

  1. @PostMapping("/test/{id}")
  2. public void testme(@PathVariable("id") String id, @RequestBody(content = @Content(examples = {
  3. @ExampleObject(
  4. name = "Person sample",
  5. summary = "person example",
  6. value =
  7. "{\"email\": \"test@gmail.Com\","
  8. + "\"firstName\": \"josh\","
  9. + "\"lastName\": \"spring...\"}"
  10. )
  11. })) 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:

  1. @PostMapping(&quot;/test/{id}&quot;)
  2. public void testme(@PathVariable(&quot;id&quot;) String id, @RequestBody(content = @Content(examples = {
  3. @ExampleObject(
  4. name = &quot;Person sample&quot;,
  5. summary = &quot;person example&quot;,
  6. value =
  7. &quot;{\&quot;email\&quot;: test@gmail.Com,&quot;
  8. + &quot;\&quot;firstName\&quot;: \&quot;josh\&quot;,&quot;
  9. + &quot;\&quot;lastName\&quot;: \&quot;spring...\&quot;&quot;
  10. + &quot;}&quot;)
  11. })) 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

  1. @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
  2. @RestController
  3. public class HelloController {
  4. /**
  5. * Test 1.
  6. *
  7. * @param hello the hello
  8. */
  9. @GetMapping("/test")
  10. @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)) }) })
  11. public void test1(String hello) {
  12. }
  13. /**
  14. * Test 2.
  15. *
  16. * @param hello the hello
  17. */
  18. @PostMapping("/test2")
  19. @RequestBody(
  20. description = "Details of the Item to be created",
  21. required = true,
  22. content = @Content(
  23. schema = @Schema(implementation = User.class),
  24. mediaType = MediaType.APPLICATION_JSON_VALUE,
  25. examples = {
  26. @ExampleObject(
  27. name = "An example request with the minimum required fields to create.",
  28. value = "min",
  29. summary = "Minimal request"),
  30. @ExampleObject(
  31. name = "An example request with all fields provided with example values.",
  32. value = "full",
  33. summary = "Full request") }))
  34. public void test2(String hello) {
  35. }
  36. }
  37. 如果您想要添加 OpenApiCustomiser 以从资源加载示例您可以从类似以下的方式开始
  38. https://github.com/springdoc/springdoc-openapi/blob/master/springdoc-openapi-javadoc/src/test/java/test/org/springdoc/api/app90/SpringDocTestApp.java
  39. @Bean
  40. public OpenApiCustomiser openApiCustomiser(Collection<Entry<String, Example>> examples) {
  41. return openAPI -> {
  42. examples.forEach(example -> {
  43. openAPI.getComponents().addExamples(example.getKey(), example.getValue());
  44. });
  45. };
  46. }
  47. 对于 headercookiequery 或者 path 参数您可以使用 @Parameterhttps://docs.swagger.io/swagger-core/v2.0.0-RC3/apidocs/io/swagger/v3/oas/annotations/Parameter.html
  48. 使用 ParameterIn 枚举https://docs.swagger.io/swagger-core/v2.0.0/apidocs/io/swagger/v3/oas/annotations/enums/ParameterIn.html
  49. 例如
  50. @Parameter(in = ParameterIn.PATH, name = "id", description="Id of the entity to be update. Cannot be empty.",
  51. required=true, examples = {@ExampleObject(name = "id value example", value = "6317260b825729661f71eaec")})
  52. 另一种方法是在您的 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

  1. @RestController
  2. public class HelloController {
  3. /**
  4. * Test 1.
  5. *
  6. * @param hello the hello
  7. */
  8. @GetMapping(&quot;/test&quot;)
  9. @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)) }) })
  10. public void test1(String hello) {
  11. }
  12. /**
  13. * Test 2.
  14. *
  15. * @param hello the hello
  16. */
  17. @PostMapping(&quot;/test2&quot;)
  18. @RequestBody(
  19. description = &quot;Details of the Item to be created&quot;,
  20. required = true,
  21. content = @Content(
  22. schema = @Schema(implementation = User.class),
  23. mediaType = MediaType.APPLICATION_JSON_VALUE,
  24. examples = {
  25. @ExampleObject(
  26. name = &quot;An example request with the minimum required fields to create.&quot;,
  27. value = &quot;min&quot;,
  28. summary = &quot;Minimal request&quot;),
  29. @ExampleObject(
  30. name = &quot;An example request with all fields provided with example values.&quot;,
  31. value = &quot;full&quot;,
  32. summary = &quot;Full request&quot;) }))
  33. public void test2(String hello) {
  34. }
  35. }

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

  1. @Bean
  2. public OpenApiCustomiser openApiCustomiser(Collection&lt;Entry&lt;String, Example&gt;&gt; examples) {
  3. return openAPI -&gt; {
  4. examples.forEach(example -&gt; {
  5. openAPI.getComponents().addExamples(example.getKey(), example.getValue());
  6. });
  7. };
  8. }

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.

  1. @Parameter(in = ParameterIn.PATH, name = &quot;id&quot;, description=&quot;Id of the entity to be update. Cannot be empty.&quot;,
  2. 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

如果仍然有兴趣的话,以下是如何在特定端点以编程方式添加示例的方法:

  1. @Bean
  2. public OpenApiCustomiser mockExamples() {
  3. return openAPI ->
  4. getRequestBodyContent(openAPI, PXL_MOCK_PATH + "/transactions", "application/json").ifPresent(request ->
  5. Arrays.stream(PxlMockCase.values()).forEach(mockCase -> {
  6. request.addExamples(
  7. mockCase.name(),
  8. new Example()
  9. .description(mockCase.getDescription())
  10. .value(TransactionCodeRequest.builder().accountId(mockCase.getAccountId()).workflowId(15).build())
  11. );
  12. }));
  13. }
  14. private Optional<MediaType> getRequestBodyContent(OpenAPI api, String path, String bodyType) {
  15. return Optional.ofNullable(api.getPaths())
  16. .map(paths -> paths.get(path))
  17. .map(PathItem::getPost)
  18. .map(Operation::getRequestBody)
  19. .map(RequestBody::getContent)
  20. .map(content -> content.get(bodyType));
  21. }
英文:

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

  1. @Bean
  2. public OpenApiCustomiser mockExamples() {
  3. return openAPI -&gt;
  4. getRequestBodyContent(openAPI, PXL_MOCK_PATH + &quot;/transactions&quot;, &quot;application/json&quot;).ifPresent(request -&gt;
  5. Arrays.stream(PxlMockCase.values()).forEach(mockCase -&gt; {
  6. request.addExamples(
  7. mockCase.name(),
  8. new Example()
  9. .description(mockCase.getDescription())
  10. .value(TransactionCodeRequest.builder().accountId(mockCase.getAccountId()).workflowId(15).build())
  11. );
  12. }));
  13. }
  14. private Optional&lt;MediaType&gt; getRequestBodyContent(OpenAPI api, String path, String bodyType) {
  15. return Optional.ofNullable(api.getPaths())
  16. .map(paths -&gt; paths.get(path))
  17. .map(PathItem::getPost)
  18. .map(Operation::getRequestBody)
  19. .map(RequestBody::getContent)
  20. .map(content -&gt; content.get(bodyType));
  21. }

答案4

得分: -4

  1. 如果我们使用Spring Boot,在我们的Maven项目中添加它,我们需要在pom.xml文件中添加依赖。
  2. <dependency>
  3. <groupId>io.springfox</groupId>
  4. <artifactId>springfox-swagger2</artifactId>
  5. <version>2.9.2</version>
  6. </dependency>
  7. <!-- -->
  8. @Configuration
  9. @EnableSwagger2
  10. public class SpringConfig {
  11. @Bean
  12. public Docket api() {
  13. return new Docket(DocumentationType.SWAGGER_2)
  14. .select()
  15. .apis(RequestHandlerSelectors.any())
  16. .paths(PathSelectors.any())
  17. .build();
  18. }
  19. }
  20. **没有使用Spring Boot的配置**
  21. @Override
  22. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  23. registry.addResourceHandler("swagger-ui.html")
  24. .addResourceLocations("classpath:/META-INF/resources/");
  25. registry.addResourceHandler("/webjars/**")
  26. .addResourceLocations("classpath:/META-INF/resources/webjars/");
  27. }
  28. **验证:**
  29. 要验证Springfox是否工作,您可以在浏览器中访问以下网址:
  30. http://localhost:8080/our-app-root/api/v2/api-docs
  31. 要使用Swagger UI,还需要另外一个Maven依赖:
  32. <dependency>
  33. <groupId>io.springfox</groupId>
  34. <artifactId>springfox-swagger-ui</artifactId>
  35. <version>2.9.2</version>
  36. </dependency>
  37. 您可以通过访问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.

  1. &lt;dependency&gt;
  2. &lt;groupId&gt;io.springfox&lt;/groupId&gt;
  3. &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;
  4. &lt;version&gt;2.9.2&lt;/version&gt;
  5. &lt;/dependency&gt;

<!-- -->

  1. @Configuration
  2. @EnableSwagger2
  3. public class SpringConfig {
  4. @Bean
  5. public Docket api() {
  6. return new Docket(DocumentationType.SWAGGER_2)
  7. .select()
  8. .apis(RequestHandlerSelectors.any())
  9. .paths(PathSelectors.any())
  10. .build();
  11. }
  12. }

Configuration Without Spring Boot

  1. @Override
  2. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  3. registry.addResourceHandler(&quot;swagger-ui.html&quot;)
  4. .addResourceLocations(&quot;classpath:/META-INF/resources/&quot;);
  5. registry.addResourceHandler(&quot;/webjars/**&quot;)
  6. .addResourceLocations(&quot;classpath:/META-INF/resources/webjars/&quot;);
  7. }

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:

  1. &lt;dependency&gt;
  2. &lt;groupId&gt;io.springfox&lt;/groupId&gt;
  3. &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;
  4. &lt;version&gt;2.9.2&lt;/version&gt;
  5. &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:

确定