6

Let's say I have I have an online store with a "shopping cart" feature and I want to implement an "empty cart" link in a RESTful way.

For simplicity, let's say my resources are a Cart that contains CartItems, each of which has a Product. My URIs might be:

# 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/

If so, what would the RESTful URI for the "empty cart" link look like?

Instead, I could think of the Cart as a general-purpose holder for Actions (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/

This approach seems more complicated than it needs to be. What would be a better way?

Community
  • 1
  • 1
Rich Apodaca
  • 28,316
  • 16
  • 103
  • 129

3 Answers3

18

Don't do the second approach. Funneling different actions through one endpoint does not feel RESTful IMO.

You have DELETE /cart_items/cart_item_id/ that removes cart_item_id from their cart. What about DELETE /cart_items/ to clear the cart itself?

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
8

Adding an item to a cart:

POST carts/{cartid}/items

Retrieving a specific item from the cart:

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

Deleting a specific item from the cart:

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

Getting the state of the cart:

GET carts/{cartid}/state

(Could return a value like 0,1 that indicates the number of items in the cart)

Emptying the cart:

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

Does this look intuitive?

Community
  • 1
  • 1
Prashanth
  • 2,404
  • 1
  • 17
  • 19
1

DELETE /cart_items/ is an interesting idea that has also been discussed here.

Rich Apodaca
  • 28,316
  • 16
  • 103
  • 129