RESTful多个更新(例如:清除购物车)?

时间:2009-01-14 20:32:29

标签: rest shopping-cart

假设我有一个带有“购物车”功能的在线商店,我希望以RESTful方式实现“空车”链接。

为简单起见,假设我的资源是一个包含CartItems的Cart,每个CartItem都有一个Product。我的URI可能是:

# add a product to the current user's Cart
POST /products/product_id/cart_items/

# remove a product from the current user's Cart
DELETE /cart_items/cart_item_id/

如果是这样,“空车”链接的RESTful URI会是什么样的?

相反,我可以将Cart视为动作的通用持有者(as described here):

# add a product
# form data contains e.g., product_id=123&action=add
POST /carts/cart_id/actions/

# remove a product
# action_id is the id of the action adding product 123
DELETE actions/action_id

# empty cart
# form data contains action=clear
POST /carts/cart_id/actions/

这种方法似乎比它需要的更复杂。什么是更好的方式?

3 个答案:

答案 0 :(得分:15)

不要做第二种方法。通过一个端点汇集不同的actions并不感觉RESTful IMO。

您有DELETE /cart_items/cart_item_id/从购物车中删除cart_item_id。那么DELETE /cart_items/清除购物车本身怎么样?

答案 1 :(得分:6)

将商品添加到购物车:

POST carts/{cartid}/items

从购物车中检索特定商品:

GET carts/{cartid}/items/{itemid}

从购物车中删除特定商品:

DELETE carts/{cartid}/items/{itemid}

了解购物车的状态:

GET carts/{cartid}/state

(可以返回类似于0的值,表示购物车中的商品数量)

清空购物车:

PUT carts/{cartid}/state?state=0

这看起来很直观吗?

答案 2 :(得分:1)

DELETE /cart_items/是一个有趣的想法,有also been discussed here