【发布时间】:2014-09-09 21:20:42
【问题描述】:
RESTful,hypertext-driven 系统需要使客户端能够创建依赖于三个或更多不同类型资源的新资源。公开此功能的最佳方法是什么?
例如,假设我经营一家在线商店。服务器知道四种资源:
- 订单:要发货的产品组。 [有一个货件]
- 目的地:运送到的位置。 [有很多货件]
- 发货:将产品发送给客户的行为。 [属于 Destination、Order 和 Packer]
- Packer:实际准备发货订单的员工。 [有很多货件]
当订单发货时,客户端需要通过在服务器上创建一个新的 Shipment 来记录此事件。货件需要注明目的地、订单和包装商。
要实现新 Shipments 的创建,我可以想到三种方法,但我不喜欢其中任何一种:
- 使用 Shipment 媒体类型 POST 到 /shipments。 Shipment 媒体类型具有三个字段:“order_uri”; "packer_uri";和“destination_uri”。每个 URI 分别用作货件中涉及的 Order、Packer 和 Destination 的唯一标识符。
- 使用 Shipment 媒体类型 POST 到 /orders/{order_id}/packers/{packer_id}/destinations/{destination_id}/shipments。
- 向系统添加一个名为“ShipmentBuilder”的新资源。使用 ShipmentBuilder 媒体类型中包含的“packer_uri”、“destination_uri”和“order_uri”发布到 /shipment_builders。
我不喜欢选项 1,因为 Shipment 媒体类型另外定义了指向 Order、Packer 和 Destination 的链接。这里,“链接”是一个 JSON 哈希,由人类可读的名称、URI 和媒体类型组成。将“order_uri”、“packer_uri”和“destination_uri”添加到媒体类型似乎不是很干,因为它复制了相关资源的 URI。
选项 2 使用深度嵌套的 URI,它们看起来既不易于维护,也不捕获任何有意义的分层信息。
选项 3 在客户端和 Shipments 的创建之间设置了另一个抽象级别,这使得系统更难学习。
如果一个 Shipment 只依赖于一个其他资源,选项 2 会更有意义,但在这种情况下它不是。就目前而言,我更喜欢选项 3,但更喜欢更好的选项。
在此示例中,创建新货件的 URI 和媒体类型的最佳组合是什么?应该考虑哪些其他方法?
更新:以下是 Shipment 资源的 JSON 示例表示,其中显示了订单、包装商和目的地的链接。选项 1 所需的 URI 重复出现在“shipment”哈希中:
{
"shipment":{
"created_at": "Wed Sep 09 18:38:31 -0700 2009",
"order_uri":"http://example.com/orders/815",
"packer_uri":"http://example.com/packers/42",
"destination_uri":"http://example.com/destinations/666"
},
"order":{
"name":"the order to which this shipment belongs",
"uri":"http://example.com/orders/815",
"media_type":"application/vnd.com.example.store.Order+json"
},
"packer":{
"name":"the person who packed this shipment",
"uri":"http://example.com/packers/42",
"media_type":"application/vnd.com.example.store.Packer+json"
},
"destination":{
"name":"the destination of this shipment",
"uri":"http://example.com/destinations/666",
"media_type":"application/vnd.com.example.store.Destination+json"
}
}
“shipment”哈希(减去“created_at”字段)的内容将被 POST。使用 GET 时,将发送上述完整的 Shipment 表示。
【问题讨论】:
-
您能否详细说明为什么您觉得将 URI 添加到货件媒体类型似乎并不干燥?我不明白你指的是什么重复。
-
Darrel,在底部添加了一些东西。
标签: rest