Magento – How to update quantity of all products in cart with REST API

cartrest

For updating a single cart item I am using a request like this:

PUT    /V1/carts/:cartId/items/:itemId

with body

{
    "cart_item": {
    "sku": "Some SKU here",
    "qty": 7,
    ...
    "quote_id": "1"
    }
}

However, this approach has several problems
– It doesn't work as a single request for updating multiple cart items, which is my main problem.
– It always adds quantity, but doesn't override, as mentioned here

I want to update the whole information once from client side, because it may not be convenient to request an update for each clicked button. Neither it's a good idea to send multiple updates at the end.

I'm new to this forum and Magento, please sorry for wrong formatting, and thank you for your time.

Best Answer

There appears to be no way to update multiple items in a cart in one request. Despite the way the cartItem" body is structured as an object, it seems to only allow updating one item at a time.

There are two ways to do it, but neither support mass updates as far as I can see.

Way #1:

PUT V1/carts/:cartId/items/:itemId

Body:

{
  "cartItem": {
    "item_id": :item_id, 
    "qty": :qty, 
    "quote_id": :cart_id
  }
}

Note: With the PUT it seems, if you have the :itemId in the URL, you don't seem to need to sku or item_id in the cartItem body. You still need the quote_id though.

Way #2:

POST V1/carts/:cartId/items

Body:

{
  "cartItem": {
    "item_id": :item_id, // this will overwrite qty
    //"sku": :my_sku, // this will increment qty
    "qty": :qty, 
    "quote_id": :cart_id
  }
}

It appears, in my testing, that the "qty" does indeed overwrite the quantity, and does not increment or add to existing quantity, if you are using item_id in both the PUT and POST versions.

However, if you use the POST version, and use the sku instead of item_id, then it will add new items to the cart, effectively "incrementing" the quantity of that product. So watch out for that.