java - 扩展单一 ID REST 端点以支持多个 ID

标签 java json rest extending multiple-input

我有一个 ID REST API,我需要对其进行扩展以支持多个(最多 10Ks)ID。基本上是对所有相关 ID 运行更新,而不是在网络中发送 10Ks 请求。

当前端点:

@POST
@Path("{id}/update")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public ResponseVO updateBlockReason(@PathParam("id") int id, List<RequestVo> requestVo) {

一个选项suggested以逗号分隔的值为 stackexchange's answers-by-ids

Usage of /answers/{ids} GET

{ids} can contain up to 100 semicolon delimited ids. To find ids programmatically look for answer_id on answer objects.

similar answers 上就是这种情况

http://our.api.com/Product/<id1>,<id2> :as James suggested can be an option since what comes after the Product tag is a parameter

但这对我和RequestVo来说似乎很尴尬所有 ID 都相同(目前 很好,但以后添加此类支持会更难)

看来我需要更改 Path 变量以将其添加到 RequestVO 中

这意味着 Id 将是一个 JSON 键,例如

[{
"id" : "1",
"name": "myAttribute"
"toggle": true
},
{
"id" : "2",
"name": "mySecondAttribute"
"toggle": false
}
]

这是正确的方法还是我遗漏了什么?

提前感谢您的任何评论\回答

当前请求VO

@Data
@AllArgsConstructor
@NoArgsConstructor
public class RequestVO {

 private String name;
 private boolean toggle;
 // will add now private int id
 }

我还担心如果我想(要求之一)使用相同的请求(如 name=doA,toggle=true)更新 10Ks ID,我将不得不复制请求 VO 而不是单独发送 ID

最佳答案

最好的方法是将 id 保留在您的 RequestVO DTO 本身中,而不是像您已经建议的那样保留在 URL 中,因为即使 URL 中有 100 个 id 也会使您的 URL 非常大你说的是 10K 个 ID。

而且在未来,单个 id 的位长度可能会增加,或者稍后您可能需要更新 50k 甚至 100K 对象。

根据 maximum length of a URL ,没有关于 URL 长度的一般规范,但过长的 URL 通常是错误的,超过 2,000 个字符的 URL 将无法在最流行的网络浏览器中运行

所以我认为您的第二种方法在这里是最好的,并且对 future 的目的也有好处。

您可能还想使用 PUT 请求,因为它对更新请求更有意义。所以你的代码会变成这样:

@PUT
@Path("/update")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public ResponseVO updateBlockReason(List<RequestVo> requestVo) {

关于java - 扩展单一 ID REST 端点以支持多个 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836226/

相关文章:

java - JAX-RS 中方法类型的最佳实践

javascript - 在没有 ARRAY 的 Node JS 中循环 JSON

ios - 在 Swift 5、iOS 14 中编码可编码结构时出现 NSJSONSerialization 错误 : Invalid top-level type in JSON write

java - 尝试返回 XML 时 Jersey 返回 500

java - Android解压功能不起作用

java - 数据库文件被锁定(Java 中的 SQL 异常)

java - Linux JVM 的 JAX WS 服务器实现性能问题?

ruby-on-rails - 使用 Active Record 搜索嵌套/多级 Postgres JSON 类型

git - Azure DevOps git 策略配置 api 损坏了吗?

rest - 当传递无效 ID 时,RESTful API 是否应返回 400 或 404