在 Quarkus 中,我需要定义一个 API,这将生成一个 Swagger-UI JSON/YAML 文件来分发给消费者。
通过在 REST 端点中定义许多注释,这可以按预期/记录地工作。例如:
@POST
@Operation(summary = "creates a new product")
@APIResponse(responseCode = "201", description = "product creation successful")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Path("/")
@RequestBody(content = @Content(examples = {
@ExampleObject(
name = CreateProductRequest.EXAMPLE1_NAME,
description = CreateProductRequest.EXAMPLE1_DESCRIPTION,
value = CreateProductRequest.EXAMPLE1_VALUE
)
}))
@APIResponse(content = @Content(examples = {
@ExampleObject(
name = CreateProductResponse.EXAMPLE1_NAME,
description = CreateProductResponse.EXAMPLE1_DESCRIPTION,
value = CreateProductResponse.EXAMPLE1_VALUE
)
}))
@ResponseStatus(201)
public CreateProductResponse create(CreateProductRequest createProductRequest) throws ValidationException {
return productManager.create(new RequestContext(1, 1), createProductRequest);
}
这样 REST-Endpoint 几乎变得不可读(这是较小的示例之一)
解决这个问题的首选方法是定义一个接口,REST-Endpoint 将实现该接口。
可以以某种方式帮助我...
我期望的工作(但没有/界面中的注释被框架完全忽略,并且不会找到生成的 swagger-json/yaml 文件的方式):
@Path("/api/v1/products")
public class ProductControllerV1 implements ProductApiV1 {
@POST
@Path("/")
@Override
public CreateProductResponse create(CreateProductRequest createProductRequest) throws ValidationException {
return productManager.create(new RequestContext(1, 1), createProductRequest);
}
}
@Tag(
name = "Product Controller V1",
description = "Product Operations, for testing many different use-cases"
)
@Path("/api/v1/products")
public interface ProductApiV1 {
@POST
@Operation(summary = "creates a new product")
@APIResponse(responseCode = "201", description = "product creation successful")
@APIResponse(responseCode = "500", description = "Server unavailable")
@Path("/")
@RequestBody(content = @Content(examples = {
@ExampleObject(
name = CreateProductRequest.EXAMPLE1_NAME,
description = CreateProductRequest.EXAMPLE1_DESCRIPTION,
value = CreateProductRequest.EXAMPLE1_VALUE
)
}))
@APIResponse(content = @Content(examples = {
@ExampleObject(
name = CreateProductResponse.EXAMPLE1_NAME,
description = CreateProductResponse.EXAMPLE1_DESCRIPTION,
value = CreateProductResponse.EXAMPLE1_VALUE
)
}))
@ResponseStatus(201)
CreateProductResponse create(CreateProductRequest createProductRequest) throws ValidationException;
您可以在 REST 控制器中尝试一下吗:
@ApplicationScoped
public class ProductControllerV1 implements ProductApiV1 {
@Override
public CreateProductResponse create(CreateProductRequest createProductRequest) throws ValidationException {
return productManager.create(new RequestContext(1, 1), createProductRequest);
}
}
维护 OpenApi 文档的另一种方法是使用混合方法。
这意味着:您将
openapi.yml
存储在 src/main/resources/META-INF
中,并使用在带注释的代码中很难完成的内容编辑此文件,并且您可以在代码上添加一些简单的注释,Quarkus 将结合这两个结果(使代码更高优先)。