REST API:嵌套资源,其 POST 副作用会创建新的(不同的)资源

REST API: Nested resource whose POST side effects create new (different) resources

我是 REST 的新手,正在尝试了解以下方法是否是公认的 RESTful 做法。

作为一个代表性示例,假设在我的域中我有一条由许多路段组成的路线。可以将新位置添加到路线中,从而在路线中创建额外的路段。另一种创建额外支路的方法是 selecting drivers。 (域将根据 driver 支持的那些创建分支)。所以:

我可以使用以下资源查看路线、路线及其路段:

GET /route/{route_id}
GET /route/{route_id}/legs

向路线添加路段时,我想显示一个位置列表,用户可以从中 select。所以我实现了一个位置资源。位置大多是静态的,由单独的系统提供。

GET /route/{route_id}/locations

所以我想采取的方法是:

POST /route/{route_id}/locations

当此资源也被发布时(以及 JOSN 表示中的到达时间等信息),它会在路线中创建新航段的域中产生副作用。

对于 drivers 它将是这样的:

GET /route/{route_id}/drivers
POST /route/{route_id}/drivers

所以在发布到:

/route/{route_id}/locations

用户将浏览到:

GET /route/{route_id}/legs

看看新腿。

这是解决上述情况的可行方法吗?

另一种选择是:

GET /route/{route_id}/legs/locations
POST /route/{route_id}/legs/locations

尽管从概念上讲这似乎没有任何不同(资源完全相同 - URL 的名称对于 REST 来说是多余的)。

我相信我自己的问题可能已经有了答案,那就是上面的做法是正确的。在阅读了一些书籍后:"RESTful Web Services" 和 "RESTful Web Services Cookbook"(均来自 O'Reilly)我遇到了他们所说的 "factory" 资源。

"A POST request is an attempt to create a new resource from an existing one. The existing resource may be the parent of the new one in a data-structure sense, the way the root of a tree is the parent of all its leaf nodes. Or the existing resource may be a special “factory” resource whose only purpose is to generate other resources. The representation sent along with a POST request describes the initial state of the new resource."

来自 Leonard Richardson 的 RESTful Web 服务;山姆 Ruby

因此,从本质上讲,位置是创造腿的工厂资源。

如果有人不同意我的阅读,我很感兴趣。