2
GET /V1/carts/mine

This API Returns information for the cart for a specified customer.

  • How to get Cart Item Images
  • Because in Mobile Application we show Product Images in CART - so how Can I get Product Images - Item wise in /V1/carts/mine REST API?
4

You can try below code for this. Although answer of @Supravat is correct but I am posting this as per my approach.

extension_attributes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Quote\Api\Data\CartItemInterface">
      <attribute code="image" type="string" />
    </extension_attributes>
</config>

di.xml //Define it under webapi_rest folder so that it will come in action for API calls only

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Quote\Api\CartRepositoryInterface">
        <plugin name="add_more_info" type="Vendor\Module\Plugin\QuotePlugin" sortOrder="10" />
    </type>
  </config>

QuotePlugin.php

<?php

/**
 * Copyright © 2018 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Vendor\Module\Plugin;

use Magento\Quote\Api\Data\CartInterface;

class QuotePlugin {

    /**
     * @var \Magento\Quote\Api\Data\CartItemExtensionFactory
     */
    protected $cartItemExtension;

    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @param \Magento\Quote\Api\Data\CartItemExtensionFactory $cartItemExtension
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     */
    public function __construct(
        \Magento\Quote\Api\Data\CartItemExtensionFactory $cartItemExtension, 
        \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepository        ) {
        $this->cartItemExtension = $cartItemExtension;
        $this->productRepository = $productRepository;
    }

    /**
     * Add attribute values
     *
     * @param   \Magento\Quote\Api\CartRepositoryInterface $subject,
     * @param   $quote
     * @return  $quoteData
     */
    public function afterGet(
    \Magento\Quote\Api\CartRepositoryInterface $subject, $quote
    ) {
        $quoteData = $this->setAttributeValue($quote);
        return $quoteData;
    }

    /**
     * Add attribute values
     *
     * @param   \Magento\Quote\Api\CartRepositoryInterface $subject,
     * @param   $quote
     * @return  $quoteData
     */
    public function afterGetActiveForCustomer(
    \Magento\Quote\Api\CartRepositoryInterface $subject, $quote
    ) {
        $quoteData = $this->setAttributeValue($quote);
        return $quoteData;
    }

    /**
     * set value of attributes
     *
     * @param   $product,
     * @return  $extensionAttributes
     */
    private function setAttributeValue($quote) {
        $data = [];
        if ($quote->getItemsCount()) {
            foreach ($quote->getItems() as $item) { 
                $data = [];
                $extensionAttributes = $item->getExtensionAttributes();
                if ($extensionAttributes === null) {
                    $extensionAttributes = $this->cartItemExtension->create();
                }
                $productData = $this->productRepository->create()->get($item->getSku());                
                $extensionAttributes->setImage($productData->getThumbnail());

                $item->setExtensionAttributes($extensionAttributes);
            }
        }

        return $quote;
    }

}

To modify any object in observer not a good approach so I did it in this way. Hope it'll work for you. Let me know if you need further help.

  • Thanks for the answer + @Ram - I'll try and update you back :) – Aditya Shah Dec 8 '18 at 11:02
  • sure @AdityaShah :) – Ramkishan Suthar Dec 8 '18 at 11:33
  • 1
    welcome @AdityaShah Happy Coding :) – Ramkishan Suthar Dec 10 '18 at 11:50
  • Can I call the same plugin for CartTotalRepositoryInterface ? – Aditya Shah Dec 10 '18 at 12:06
  • 1
    For this you need to create new plugin and new extension attribute of TotalItemInterface because TotalRepositoryInterface doesn't return CartItemInterface. – Ramkishan Suthar Dec 10 '18 at 12:11
2

GET /V1/carts/mine

Implementation Notes

Returns information for the cart for a specified customer.

Response:

{
  "id": 0,
  "created_at": "string",
  "updated_at": "string",
  "converted_at": "string",
  "is_active": true,
  "is_virtual": true,
  "items": [
    {
      "item_id": 0,
      "sku": "string",
      "qty": 0,
      "name": "string",
      "price": 0,
      "product_type": "string",
      "quote_id": "string",
      "product_option": {
        "extension_attributes": {
          "custom_options": [
            {
              "option_id": "string",
              "option_value": "string",
              "extension_attributes": {
                "file_info": {
                  "base64_encoded_data": "string",
                  "type": "string",
                  "name": "string"
                }
              }
            }
          ],
          "bundle_options": [
            {
              "option_id": 0,
              "option_qty": 0,
              "option_selections": [
                0
              ],
              "extension_attributes": {}
            }
          ],
          "configurable_item_options": [
            {
              "option_id": "string",
              "option_value": 0,
              "extension_attributes": {}
            }
          ],
          "downloadable_option": {
            "downloadable_links": [
              0
            ]
          },
          "giftcard_item_option": {
            "giftcard_amount": "string",
            "custom_giftcard_amount": 0,
            "giftcard_sender_name": "string",
            "giftcard_recipient_name": "string",
            "giftcard_sender_email": "string",
            "giftcard_recipient_email": "string",
            "giftcard_message": "string",
            "extension_attributes": {}
          }
        }
      },
      "extension_attributes": {
        "negotiable_quote_item": {
          "item_id": 0,
          "original_price": 0,
          "original_tax_amount": 0,
          "original_discount_amount": 0,
          "extension_attributes": {}
        }
      }
    }
  ],
  "items_count": 0,
  "items_qty": 0,
  "customer": {
    "id": 0,
    "group_id": 0,
    "default_billing": "string",
    "default_shipping": "string",
    "confirmation": "string",
    "created_at": "string",
    "updated_at": "string",
    "created_in": "string",
    "dob": "string",
    "email": "string",
    "firstname": "string",
    "lastname": "string",
    "middlename": "string",
    "prefix": "string",
    "suffix": "string",
    "gender": 0,
    "store_id": 0,
    "taxvat": "string",
    "website_id": 0,
    "addresses": [
      {
        "id": 0,
        "customer_id": 0,
        "region": {
          "region_code": "string",
          "region": "string",
          "region_id": 0,
          "extension_attributes": {}
        },
        "region_id": 0,
        "country_id": "string",
        "street": [
          "string"
        ],
        "company": "string",
        "telephone": "string",
        "fax": "string",
        "postcode": "string",
        "city": "string",
        "firstname": "string",
        "lastname": "string",
        "middlename": "string",
        "prefix": "string",
        "suffix": "string",
        "vat_id": "string",
        "default_shipping": true,
        "default_billing": true,
        "extension_attributes": {},
        "custom_attributes": [
          {
            "attribute_code": "string",
            "value": "string"
          }
        ]
      }
    ],
    "disable_auto_group_change": 0,
    "extension_attributes": {
      "company_attributes": {
        "customer_id": 0,
        "company_id": 0,
        "job_title": "string",
        "status": 0,
        "telephone": "string",
        "extension_attributes": {}
      },
      "is_subscribed": true
    },
    "custom_attributes": [
      {
        "attribute_code": "string",
        "value": "string"
      }
    ]
  },
  "billing_address": {
    "id": 0,
    "region": "string",
    "region_id": 0,
    "region_code": "string",
    "country_id": "string",
    "street": [
      "string"
    ],
    "company": "string",
    "telephone": "string",
    "fax": "string",
    "postcode": "string",
    "city": "string",
    "firstname": "string",
    "lastname": "string",
    "middlename": "string",
    "prefix": "string",
    "suffix": "string",
    "vat_id": "string",
    "customer_id": 0,
    "email": "string",
    "same_as_billing": 0,
    "customer_address_id": 0,
    "save_in_address_book": 0,
    "extension_attributes": {
      "gift_registry_id": 0
    },
    "custom_attributes": [
      {
        "attribute_code": "string",
        "value": "string"
      }
    ]
  },
  "reserved_order_id": 0,
  "orig_order_id": 0,
  "currency": {
    "global_currency_code": "string",
    "base_currency_code": "string",
    "store_currency_code": "string",
    "quote_currency_code": "string",
    "store_to_base_rate": 0,
    "store_to_quote_rate": 0,
    "base_to_global_rate": 0,
    "base_to_quote_rate": 0,
    "extension_attributes": {}
  },
  "customer_is_guest": true,
  "customer_note": "string",
  "customer_note_notify": true,
  "customer_tax_class_id": 0,
  "store_id": 0,
  "extension_attributes": {
    "shipping_assignments": [
      {
        "shipping": {
          "address": {
            "id": 0,
            "region": "string",
            "region_id": 0,
            "region_code": "string",
            "country_id": "string",
            "street": [
              "string"
            ],
            "company": "string",
            "telephone": "string",
            "fax": "string",
            "postcode": "string",
            "city": "string",
            "firstname": "string",
            "lastname": "string",
            "middlename": "string",
            "prefix": "string",
            "suffix": "string",
            "vat_id": "string",
            "customer_id": 0,
            "email": "string",
            "same_as_billing": 0,
            "customer_address_id": 0,
            "save_in_address_book": 0,
            "extension_attributes": {
              "gift_registry_id": 0
            },
            "custom_attributes": [
              {
                "attribute_code": "string",
                "value": "string"
              }
            ]
          },
          "method": "string",
          "extension_attributes": {}
        },
        "items": [
          {
            "item_id": 0,
            "sku": "string",
            "qty": 0,
            "name": "string",
            "price": 0,
            "product_type": "string",
            "quote_id": "string",
            "product_option": {
              "extension_attributes": {
                "custom_options": [
                  {
                    "option_id": "string",
                    "option_value": "string",
                    "extension_attributes": {
                      "file_info": {
                        "base64_encoded_data": "string",
                        "type": "string",
                        "name": "string"
                      }
                    }
                  }
                ],
                "bundle_options": [
                  {
                    "option_id": 0,
                    "option_qty": 0,
                    "option_selections": [
                      0
                    ],
                    "extension_attributes": {}
                  }
                ],
                "configurable_item_options": [
                  {
                    "option_id": "string",
                    "option_value": 0,
                    "extension_attributes": {}
                  }
                ],
                "downloadable_option": {
                  "downloadable_links": [
                    0
                  ]
                },
                "giftcard_item_option": {
                  "giftcard_amount": "string",
                  "custom_giftcard_amount": 0,
                  "giftcard_sender_name": "string",
                  "giftcard_recipient_name": "string",
                  "giftcard_sender_email": "string",
                  "giftcard_recipient_email": "string",
                  "giftcard_message": "string",
                  "extension_attributes": {}
                }
              }
            },
            "extension_attributes": {
              "negotiable_quote_item": {
                "item_id": 0,
                "original_price": 0,
                "original_tax_amount": 0,
                "original_discount_amount": 0,
                "extension_attributes": {}
              }
            }
          }
        ],
        "extension_attributes": {}
      }
    ],
    "negotiable_quote": {
      "quote_id": 0,
      "is_regular_quote": true,
      "status": "string",
      "negotiated_price_type": 0,
      "negotiated_price_value": 0,
      "shipping_price": 0,
      "quote_name": "string",
      "expiration_period": "string",
      "email_notification_status": 0,
      "has_unconfirmed_changes": true,
      "is_shipping_tax_changed": true,
      "is_customer_price_changed": true,
      "notifications": 0,
      "applied_rule_ids": "string",
      "is_address_draft": true,
      "deleted_sku": "string",
      "creator_id": 0,
      "creator_type": 0,
      "original_total_price": 0,
      "base_original_total_price": 0,
      "negotiated_total_price": 0,
      "base_negotiated_total_price": 0,
      "extension_attributes": {}
    }
  }
}

If you see the above response , there is no product image information. So we should call an API for it. You should call GET /V1/products/:sku/media to retrieve for a product's image.

For for information please see here :

Magento 2 REST APIs

enter image description here

[Edit]

Magento 2 rest api : Get cart items with images

Follow the Steps to get Product thumbnail Image in Cart through Rest API without POST any values. It will take current thumbnail Image of a product. Rest Url :

Method : GET -> rest/V1/guest-carts/3f260b6e818d2fe56894ed6222e433f8/items

Create a module : code/Vendor_name/Module_name/

registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Hopescode_Mobileshop',
    __DIR__
);

create module.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2018-2019 Hopescode. All rights reserved.
 */
-->

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
        <module name="Hopescode_Mobileshop" setup_version="1.0.0" />
    </config>

create etc/extension_attributes.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2018-2019 Hopescode, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">

    <extension_attributes for="Magento\Quote\Api\Data\CartItemInterface">
        <attribute code="image_url" type="string" />
    </extension_attributes>

</config>

create etc/events.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2018-2019 Hopescode, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_quote_load_after">
        <observer name="hopescode_mobileshop_sales_quote_load_after" instance="Hopescode\Mobileshop\Observer\ProductInterface" />
    </event>
</config>

Create Observer: Vendor_name/Mocule_name/Observer/

ProductInterface.php

<?php
/**
 * Copyright © 2018-2019 Hopescode, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Hopescode\Mobileshop\Observer;

use Magento\Framework\Event\ObserverInterface;
    use Magento\Catalog\Api\ProductRepositoryInterfaceFactory as ProductRepository;
    use Magento\Catalog\Helper\ImageFactory as ProductImageHelper;
    use Magento\Store\Model\StoreManagerInterface as StoreManager;
    use Magento\Store\Model\App\Emulation as AppEmulation;
    use Magento\Quote\Api\Data\CartItemExtensionFactory;

    class ProductInterface implements ObserverInterface
    {   
        /**
         * @var ObjectManagerInterface
         */
        protected $_objectManager;

        /**
         * @var ProductRepository
         */
        protected $productRepository;

        /**
         *@var \Magento\Catalog\Helper\ImageFactory
         */
        protected $productImageHelper;

        /**
         *@var \Magento\Store\Model\StoreManagerInterface
         */
        protected $storeManager;

        /**
         *@var \Magento\Store\Model\App\Emulation
         */
        protected $appEmulation;

        /**
         * @var CartItemExtensionFactory
         */
        protected $extensionFactory;

        /**
         * @param \Magento\Framework\ObjectManagerInterface $objectManager
         * @param ProductRepository $productRepository
         * @param \Magento\Catalog\Helper\ImageFactory
         * @param \Magento\Store\Model\StoreManagerInterface
         * @param \Magento\Store\Model\App\Emulation
         * @param CartItemExtensionFactory $extensionFactory
         */
        public function __construct(
            \Magento\Framework\ObjectManagerInterface $objectManager,
            ProductRepository $productRepository,
            ProductImageHelper $productImageHelper,
            StoreManager $storeManager,
            AppEmulation $appEmulation,
            CartItemExtensionFactory $extensionFactory
        ) {
            $this->_objectManager = $objectManager;
            $this->productRepository = $productRepository;
            $this->productImageHelper = $productImageHelper;
            $this->storeManager = $storeManager;
            $this->appEmulation = $appEmulation;
            $this->extensionFactory = $extensionFactory;
        }

    public function execute(\Magento\Framework\Event\Observer $observer, string $imageType = NULL)
        {
            $quote = $observer->getQuote();

           /**
             * Code to add the items attribute to extension_attributes
             */
            foreach ($quote->getAllItems() as $quoteItem) {
                $product = $this->productRepository->create()->getById($quoteItem->getProductId());
                $itemExtAttr = $quoteItem->getExtensionAttributes();
                if ($itemExtAttr === null) {
                    $itemExtAttr = $this->extensionFactory->create();
                }


                $imageurl =$this->productImageHelper->create()->init($product, 'product_thumbnail_image')->setImageFile($product->getThumbnail())->getUrl();



                $itemExtAttr->setImageUrl($imageurl);
                $quoteItem->setExtensionAttributes($itemExtAttr);
            }
            return;
        }

        /**
         * Helper function that provides full cache image url
         * @param \Magento\Catalog\Model\Product
         * @return string
         */
        protected function getImageUrl($product, string $imageType = NULL)
        {
            $storeId = $this->storeManager->getStore()->getId();

            $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
            $imageUrl = $this->productImageHelper->create()->init($product, $imageType)->getUrl();

            $this->appEmulation->stopEnvironmentEmulation();

            return $imageUrl;
        }

    }

Output :

[
    {
        "item_id": 5,
        "sku": "samplepro",
        "qty": 1,
        "name": "samplepro",
        "price": 1500,
        "product_type": "simple",
        "quote_id": "3f260b6e818d2fe56894ed6222e433f8",
        "extension_attributes": {
            "image_url": "http://localhost/dashboard/myapi/pub/media/catalog/product/cache//beff4985b56e3afdbeabfc89641a4582/n/u/nutro_crunchy_real_apple.jpg"
        }
    }
]

Before checking your out put, If you installed the correct method you can check your var/generation/Magento/Quote/Api/Data/CartItemExtension.php has the value like this:

<?php
namespace Magento\Quote\Api\Data;

/**
 * Extension class for @see \Magento\Quote\Api\Data\CartItemInterface
 */
class CartItemExtension extends \Magento\Framework\Api\AbstractSimpleObject implements \Magento\Quote\Api\Data\CartItemExtensionInterface
{
    /**
     * @return string|null
     */
    public function getImageUrl()
    {
        return $this->_get('image_url');
    }

    /**
     * @param string $imageUrl
     * @return $this
     */
    public function setImageUrl($imageUrl)
    {
        $this->setData('image_url', $imageUrl);
        return $this;
    }
}
  • I want those image data in /V1/carts/mine API itself. I am aware about getbyID and sku APIs :) – Aditya Shah Dec 8 '18 at 8:46
  • @AdityaShah, Then you should develop a custom module for it. – Supravat M Dec 8 '18 at 9:15
  • @AdityaShah I update my answer. – Supravat M Dec 8 '18 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.