Question

One of the rest key principle is not to maintain state on a server or to communicate statelessly. I want to have views how this principle works on shopping cart? So, say if the user is adding products in a shopping cart from a shopping website. In my opinion, the server will have some implementation to have shopping cart in session scope and user will send a post call to add the product in a shopping cart. For e.g /shoppingcart/products/1. Now the products remain added in shopping cart(but not persisted in database) until user confirms for checkout. During confirmation of check-out, the shopping cart items gets persisted into the database on server side.

Does this approach(putting item in shopping cart on server side that is in session scope) violates rest principle? If yes, how then we can implement the adding product to shopping cart by taking care of "stateless" communication principle?

Was it helpful?

Solution

A shopping cart should be handled as a resource, and products added/removed just as you may add or remove associations between any two resources in REST. Instead of the client saying "now purchase the items in my cart" the client should say "now purchase the items in cart #187462". Assign each cart a URL, and have your operations act upon that resource instead of some product array tied to the current session.

An alternative which is also stateless is to have the client track all items in the cart, but this means the user cannot leave the cart (abandon it) on one computer and resume shopping on another device.

Addendum: Remember that permissions/access control can be assigned independently. Sure, each cart has a URL, but be sure to make it so that the logged in user can only see cart resources that they have created.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top