设计具有多个 id 的 RESTful 服务 [英] Design RESTful service with multiple ids
问题描述
我正在设计一个 RESTful 服务.它是列出一组数据.主要问题是该集合没有合理的单一标识符.也不能在系统知识范围内轻松计算特定集合.因此,似乎不可能有 GET/items/{identifier} 服务.
I am designing a RESTful service. It is to list a set of data. The main problem is that the set does not have a reasonable, single identifier. Nor can the specific set be easily calculated within the knowledge of the system. As a result, it does not seem possible to have a GET /items/{identifier} service.
我确实有被请求的每个元素的 ID.我的主要问题是在 URI 中列出 ids 似乎不是 RESTful(例如 GET items/{id1},{id2},...,{idn} ).对吗?
I do have the id of each element being requested. My main issue is that it does not seem RESTful to list the ids in the URI (eg GET items/{id1},{id2},...,{idn} ). Right?
我可以看到 DELETE 有一个类似的用例 - 在一个请求周期中删除多个项目.
I could see DELETE having a similar use case - remove multiple items in one request cycle.
在 REST 领域内如何满足这样的用例?这可能吗?
How would such a use case be satisfied while staying within the REST realm? Is that possible?
推荐答案
问题中陈述的方法实际上意味着对于 ids
的每个组合都有一个资源.假设我们有 2 个 ids
:1 和 2.
The approach stated in the question actually means that for each combination of ids
there is a resource. Let's say we have 2 ids
: 1 and 2.
/items/1,2
/items/2,1
以上代表不同的资源,虽然结果是一样的.这可能会让 API 的使用者感到困惑.
The above represent different resources, although the result is the same. This might be confusing for the consumer of the API.
另一种建模方法是通过查询参数作为过滤语义.假设 id
实际上是资源的一个字段.
Another way to model this is via query parameter as filtering semantics.
Let's assume, that the id
is actually a field of a resource.
示例,通过 id
1 获取 item
:
Example, getting item
by id
1:
GET
/items/1
Response:
{
"id": 1,
"type": "table",
"color": "black",
...
}
那么问题是,如果我需要批量获取多件物品怎么办?您可以将此问题概括为按某些字段的值过滤 items
的一般问题.例如:获取 table
So the question is, what if I need to get several items as a bulk?
You can generalize this question to the general question of filtering items
by values on certain fields.
E.g.: getting all the items
of type table
GET
/items?query="name='table'"
Response:
{
"data": [
{
"id": 1,
"type": "table",
"color": "black",
...
},
{
"id": 2,
"type": "table",
"color": "grey",
...
},
{
"id": 6,
"type": "table",
"color": "brown",
...
}
]
}
所以同样的问题可以被问到获取items
,其中id
是1
或2
.假设我们在 query
So the same question can be asked for getting items
where id
is 1
or 2
.
Let's say we model the or operation as ||
in the syntax of query
GET
/items?query="id=1||id=2"
Response:
{
"data": [
{
"id": 1,
"type": "table",
"color": "black",
...
},
{
"id": 2,
"type": "table",
"color": "grey",
...
}
]
}
这篇关于设计具有多个 id 的 RESTful 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!