Magento 2 REST API – How to Add Custom Option to Cart Item

cartmagento2ordersquoterest

I am using Magento 2 default quoteCartItem restful APIs to add, delete and update items in cart. Things are working as expected.

GET /V1/carts/{cartId}/items
POST /V1/carts/{cartId}/items
DELETE /V1/carts/{cartId}/items/{itemId}
PUT /V1/carts/{cartId}/items/{itemId}
GET /V1/carts/mine/items
POST /V1/carts/mine/items
DELETE /V1/carts/mine/items/{itemId}

Now, I have to add an identifier/flag to identify whether the user has chosen the item as home delivery or self pick-up.

  • What are the quote item options and when we need it?
  • How to add custom attribute/option to quote item?
  • Is there any in-built API, which I can use achieve my requirement?
  • Do I need to write Custom API for this?

I'm new in magento 2, not too familiar with technical keywords. Hope I explained this question properly.

Best Answer

I have working with magento2 API and below ans could be something useful for you.

Step1: First of all you need to generate an empty cart for customer. If customer is already registered then you need to pass customer_id as an parameter like below.

Request URL: http://magentohost/rest/V1/carts/mine
parameters: {"customer_id":"7"} //your customer_id goes here.
Response: "9" is quote id. // This will return Quote Id.

It will return quote id as a response.

Step2: For adding a product to cart with custom options you need to call below url

Request URL: http://magentohost/rest/V1/carts/mine/items

parameters: {
    "cart_item": {
        "quote_id": "9",
        "sku": "24-MB01",
        "qty": 1,
        "productOption":{
            "extensionAttributes":{
                "customOptions":[
                    {
                        "optionId":"1",
                        "optionValue":"2"
                    }
                    ]
            }
        }
    }
}

Response:

{
  "item_id": 9,
  "sku": "24-MB01",
  "qty": 1,
  "name": "Joust Duffle Bag",
  "product_type": "simple",
  "quote_id": "9",
  "product_option": {
    "extension_attributes": {
      "custom_options": [
        {
          "option_id": "1",
          "option_value": "2"
        }
      ]
    }
  }
}

Refer Link: https://github.com/magento/magento2/issues/4381 .

I have tested it with postman which gives me cart with added custom option in it. Magento provides default API to add custom options in cart so there wont be need to add custom API for the same.
Also here is link which would be helpful for the same.
http://devdocs.magento.com/swagger/index.html#/

quoteCartItemRepositoryV1

Related Topic