gpt4 book ai didi

REST API 设计 - 在资源的数组字段中添加/删除项目

转载 作者:行者123 更新时间:2023-12-02 04:39:14 25 4
gpt4 key购买 nike

假设我们有以下 REST 资源收集端点:

/products

资源看起来像这样:

GET /products/123
Accept: application/json

{
"id": "123",
"name": "Shampoo",
...
"ingredients": [
"Sodium Lauryl Sulfate",
"Sodium Laureth Sulfate",
"Hydrochloric Acid",
...
]
}

现在,假设我想更新资源,并在 ingredients 字段中添加或删除一种成分。一种方法是GET 资源,操作数组,然后PUTPATCH 返回。然而,这是一个非常繁琐的协议(protocol),如果数组太大,它也会带来可扩展性问题。

在没有源数组的情况下实现此添加/删除操作的最佳方法是什么?

我已经探索了以下内容:JSON Patch Specification但似乎规范不是 REST。它使用相同的资源具有不同的“操作”,如表示,这与资源的表示完全不同。

我想尽可能地为 PUT/PATCH 方法保留相同的资源表示,因为它出现在 GET 中。

这是我对此事的看法。

  1. string类型项改为object
  2. 将元字段添加到名为$op的对象

所以在这个设计中,资源在 GET

上的样子
GET /products/123
Accept: application/json

{
"id": "123",
"name": "Shampoo",
...
"ingredients": [
{
"name": "Sodium Lauryl Sulfate"
},
{
"name": "Sodium Laureth Sulfate"
},
{
"name": "Hydrochloric Acid"
},
...
]
}

现在如果我想从 ingredients 数组中删除一个项目:

PATCH /products/123
Content-Type: application/json
Accept: application/json

{
"ingredients": [
{
"$op": "remove",
"name": "Hydrochloric Acid"
}
]
}

或者加回去:

PATCH /products/123
Content-Type: application/json
Accept: application/json

{
"ingredients": [
{
"$op": "add",
"name": "Hydrochloric Acid"
}
]
}

谁有更好的办法?关于这个主题有一些标准吗?

最佳答案

在我看来,最好的解决方案是为产品成分管理提供另一个 REST 端点。当您还以 HATEOAS 方式提供链接时,您将能够在获得产品资源后立即完全控制该阵列。

考虑这个表示:

GET /products/123
Accept: application/json

{
"id": "123",
"name": "Shampoo",
...
"ingredients": [
{
"name": "Sodium Lauryl Sulfate"
"links": [
{
"rel": "self",
"href": "/products/123/ingredients/1"
}
]
},
{
"name": "Sodium Laureth Sulfate",
"links": [
{
"rel": "self",
"href": "/products/123/ingredients/2"
}
]
},
...
],
"links": [
{
"rel": "self",
"href": "/products/123"
},
{
"rel": "ingredients",
"href": "/products/123/ingredients"
}
]
}

有了它,您就可以向产品中添加新成分...

POST /products/123/ingredients
Content-Type: application/json
Accept: application/json

{
"name": "Hydrochloric Acid"
}

...或删除现有的。

DELETE /products/123/ingredients/2

What is the best way to achieve this add / remove operation without having the source array?

如果您从产品的 JSON 表示中删除成分数组并只留下指向它的链接,您仍然可以立即添加新成分。

删除操作仍然需要源数组,但您可以异步下载它。事实上,我认为在不先拥有它的情况下从数组中删除任何东西是没有意义的。你怎么知道你试图去除的成分在里面?

最好的问候

关于REST API 设计 - 在资源的数组字段中添加/删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com