nirvair
nirvair

Reputation: 4180

How to replace session with stateless rest apis?

So, I am trying to make a shopping cart web architecture on rest framework where I am struggling to use browser storages to use as an alternative to maintaining the state.

I tried the window.localStorage and window.sessionStorage() APIs but it failed in the case of the private browsing mode in Safari and Opera.

So can anyone help out in the figuring other methods by which I can maintain states in rest based architecture?

Upvotes: 0

Views: 349

Answers (1)

user5547025
user5547025

Reputation:

You don't need sessions to store application state. User resources.

On approach would be to model every shopping cart as a resource with a unique ID:

/shop/shoppingcarts/E73AC56C-BDF7-11E5-81F1-8E2EDB915C80

The client application in the browser would read this resource:

GET /shop/shoppingcarts/E73AC56C-BDF7-11E5-81F1-8E2EDB915C80

It would add an item to the cart:

POST /shop/shoppingcarts/E73AC56C-BDF7-11E5-81F1-8E2EDB915C80/items

{
  "itemId": "1234",
  "quantity": 1
}

It would list the contents of the shopping cart:

GET /shop/shoppingcarts/E73AC56C-BDF7-11E5-81F1-8E2EDB915C80/items

[
  {
    "itemId": "1234",
    "title": "Some nice item",
    "quantity": 1,
    "price", 12.34,
    "priceTotal": 12.34
  },
  {
    "itemId": "9876",
    "title": "Some other nice item",
    "quantity": 2,
    "price", 0.99,
    "priceTotal": 1.98
  }
]

The web application would remove an item from the cart:

DELETE /shop/shoppingcarts/E73AC56C-BDF7-11E5-81F1-8E2EDB915C80/items/9876

I think you get the idea.

Upvotes: 1

Related Questions