![](/img/trans.png)
[英]How to add Header with Authorization for springdoc-openapi endpoint calls
[英]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) {
}
我需要找到一種方法如何在PagingAndSorting
object 的Swagger
示例中顯示。
我正在使用springdoc-api
v1.4.3。
您可以使用@ExampleObject 注釋。
請注意,如果您想引用現有示例 object,您也可以在示例中使用 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) { }
如果您在 controller 中使用@RequestBody
Spring 注釋,則需要區分兩者,例如,通過對 Swagger 注釋使用@io.swagger.v3.oas.annotations.parameters.RequestBody
。 這可以防止下面評論中提到的 null 參數問題。
@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/測試/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());
});
};
}
對於 header、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/
如果有人仍然感興趣,這就是如何以編程方式將示例添加到特定端點:
@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));
}
如果我們使用 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();
}
}
沒有 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/");
}
驗證:驗證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 在瀏覽器中對其進行測試
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.