.Net Core(现在称为 .Net 8 或更高版本)有一个很好的小注释,名为
ProducesResponseType
。
它可以让您明确地指示 REST 端点可以返回什么。当您为客户端使用自动生成工具时,它会很有帮助:不仅是响应类,而且还包括整个服务类(它知道如何处理每个http代码)。
请注意,它不仅指示类型或 http 代码,还指示两者的可能组合:
[ProducesResponseType(typeof(DepartmentDto), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
我想知道我在 Java 中的选择是什么。 普通 Java、JAX-RS 或 Spring。
目前我的遗留代码如下所示(如下)。
@Produces
是一个开始,但不如ProducesResponseType
机制那么完整。
@PUT
@Path("/my-endpoint/{id}")
@Produces({MediaType.APPLICATION_JSON,})
@Consumes(MediaType.APPLICATION_JSON)
public Response doTheThing(...
如果您的客户端是基于 OpenAPI 描述生成的,您可以对您的方法进行类似于以下的注释:
@GET
@Produces(MediaType.APPLICATION_JSON)
@APIResponseSchema(value = InventoryList.class,
responseDescription = "host:properties pairs stored in the inventory.",
responseCode = "200")
@Operation(
summary = "List inventory contents.",
description = "Returns the currently stored host:properties pairs in the "
+ "inventory.")
public InventoryList listContents() {
return manager.list();
}
查看本教程以获取一些一般信息 - https://openliberty.io/guides/microprofile-openapi.html#augmenting-the-existing-jakarta-restful-web-services-annotations-with-openapi-annotations
但这里又需要使用 OpenAPI/Swagger。它不是原生的,也不是 JAX-RS 的一部分。
@Operation(
summary = "Get location information",
tags = {"Information"},
responses = {
@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = LocationResponse.class)), description = "Get location information"),
@ApiResponse(responseCode = "500", description = "Error: Internal Server Error")
}
)