2

I'm a little confused as to what the collection URI's should return.

Say I have a collection, /users of decently large elements. Then we have the expected:

GET /users/123           // returns user element with identifier 123

But what should

GET /users

return? If the collection is large, and the elements are large, it's probably not a good thing to return all elements. Perhaps instead, GET requests at the /users level should return element summaries (identifiers and possibly a few properties), while GET requests at the /users/ level should return actual elements. Then you could do something like;

GET /users
   > [{name: abc, id: 1}, {name: def, id: 2}, {name: ghi, id: 3}, ...]
GET /users/2
   > {name: def, prop1: *, prop2: *, ...}

Which could be a good way to lazily load data if you wanted to preview important application-domain properties before requesting them in their entirety. With this, in order to apply queries, you'd do something like

GET /users?prop1=value           // returns element summaries of elements with prop1=value
GET /users/?prop1=value          // returns elements with prop1 = value

Is this approach OK? Or do the other methods acting on /users then loose meaning.. (ex. PUT /users ?)

4

1 回答 1

2

我个人喜欢 /users 不返回所有用户但返回查询特定用户所需的信息的风格。因此,摘要方法是我通常会如何编写它。

如果您要过滤或查询,我会选择您提供的第一个:

GET /users?prop1=value

我不在乎第二个

GET /users/?prop1=value

因为它很容易被误解或导致令人困惑和意想不到的错误(缺少一个斜线仍然有效,但会完全改变结果)。

您可能希望使用替代 URL 的方法来根据搜索参数返回特定用户,例如

GET /users?prop1=value    // returns element summaries based on results of prop1 matching
GET /users/find?prop1=value // returns elements with prop1 = value

显然,您的措辞可能会改变(查找/搜索),或者您可以使用完全不同的 URI,但我尽量避免两个不同的含义是一个字符/符号分开的事情,以避免意外错误。另一种选择是确保您在提供的文档中清楚地概述了这一点,以便任何使用您的 API 的人都会意识到这种潜力。

实际上对此进行扩展,我将使用 all 构造。

因此,我不使用查找/搜索,而是提供:

GET /users                   // returns summaries
GET /users/#                 // returns element
GET /users/all               // returns all elements
GET /users/all?prop1=value   // returns all elements that match the filter
于 2013-09-11T21:45:21.197 回答