7

简单的问题,我很难找到答案..

如果我有一个 REST Web 服务,并且我的设计没有使用 url 参数,我如何指定两个不同的键来返回相同的资源?

我想要的示例(并且已经实现)

/Person/{ID}

它按预期返回一个人。

现在我也想要

/Person/{Name}

它按姓名返回一个人。

这是正确的 RESTful 格式吗?或者是这样的:

/Person/Name/{Name}
4

3 回答 3

6

您应该只使用一个 URI 来引用单个资源。拥有多个 URI 只会造成混乱。在您的示例中,由于两个人的名字相同,会引起混淆。他们指的是哪个人员资源?

也就是说,您可以让多个 URI 引用单个资源,但对于“真实”URI 以外的任何内容,您都应该使用301 - Moved Permanently.

就个人而言,我永远不会实现多 ID 方案或重定向来支持它。选择一个单一的识别方案并坚持下去。您的 API 的用户会感谢您。

您真正需要构建的是查询 API,因此请关注如何实现资源之类的东西,该/personFinder资源可以将名称作为参数并/person/{ID}在响应中返回潜在的多个匹配 URI。

于 2012-06-19T18:21:11.223 回答
1

我想从技术上讲,你可以让两个 URI 指向同一个资源(也许其中一个作为规范资源),但我认为你不想从实现的角度这样做。如果 ID 和名称之间存在重叠怎么办?

它确实看起来是一个使用查询参数的好地方,但如果你坚持不这样做,也许你可以这样做

person/{ID} 

personByName/{Name}
于 2012-06-19T16:03:45.477 回答
0

我通常同意这个答案,为了清晰和一致,最好避免多个 id 指向同一个实体。

然而,有时这种情况自然会出现。我使用的一个例子是波兰公司,可以通过他们的税号('NIP' 号)或他们的国家商业登记号('KRS' 号)来识别。

在这种情况下,我认为应该首先将辅助 id 作为标准添加到搜索端点。因此,用户将能够在辅助 ID 和主 ID 之间“转换”。

However, if users still keep insisting on being able to retrieve an entity directly by the secondary id (as we experienced), one other possibility is to provide a "secret" URL, not described in the documentation, performing such an operation. This can be given to users who made the effort to ask for it, and the potential ambiguity and confusion is then on them, if they decide to use it, not on everyone reading the documentation.

In terms of ambiguity and confusion for the API maintainer, I think this can be kept reasonably minimal with a helper function to immediately detect and translate the secondary id to primary id at the beginning of each relevant API endpoint.

It obviously matters much less than normal what scheme is chosen for the secret URL.

于 2020-11-24T11:34:41.860 回答