Is it acceptable to use POST for adding to a quantity and DELETE for removing from it in a RESTful service?

0
17
Asked By CuriousCoder22 On

I'm new to RESTful services and have a question about how to manage items in a shopping cart. For instance, can I use POST to increase the quantity of an item in the cart and DELETE to decrease it? Here's how I thought it could work:

- Using POST to /api/cartId with a request body like {itemId, quantity} would respond with the updated quantity—adding the new quantity to the existing one.
- Using DELETE on /api/cartId with a request body of {itemId, quantity} would decrease the existing quantity based on the specified amount.

Is this approach valid within the REST framework? Thanks for any insights!

4 Answers

Answered By CodeWiz88 On

Normally, PATCH is the go-to method for updating existing resources. It sounds like your use case could benefit from it. However, there's no strict standard in practice; it often comes down to how your API is designed.

For more complex scenarios, you might also want to consider alternatives like GraphQL. It lets you handle data more dynamically.

Answered By LogicGuru99 On

Using DELETE to modify quantities can lead to confusion, especially since DELETE usually communicates that something is being completely removed. Instead, I would suggest looking into using PATCH for partial updates to existing resources—that's what it’s designed for!

POST is typically for creating new resources, while PATCH lets you adjust them, including quantities.

Answered By APIDesigner4Life On

If you're aiming for a single endpoint approach, you could modify your POST request to specify actions. For example, you could include a quantityAdd field in the request body to indicate whether to increase or set a quantity.

Alternatively, you might consider separate endpoints for clarity, like:
- POST /api/{cartId}/{itemId}/qty/{qty} for setting quantity
- POST /api/{cartId}/{itemId}/qtyAdd/{qty} to add to the existing quantity.

Just remember, consistency is key when designing your API!

Answered By TechSavvy101 On

From a strict REST perspective, that’s not really the right approach. DELETE is meant to be idempotent, meaning if you run the same command multiple times, it should have the same effect as running it once. So, using DELETE to adjust quantities isn’t standard practice.

But here’s the thing: there aren’t any REST police enforcing these rules. If your application works without issues, you're pretty safe. Just be cautious of potential weirdness with any middleware you're using.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.