4

In rest api, I am using "/rest/V1/guest-carts/e3e1fd447e0e315dd761942cf949ce5d/items" method to get the magento cart items. It works well and the result is

  [
    {
      "item_id": 100,
      "sku": "abc-1",
      "qty": 1,
      "name": "Product one",
      "price": 19,
      "product_type": "simple",
      "quote_id": "e3e1fd447e0e315dd761942cf949ce5d"
    },
    {
      "item_id": 101,
      "sku": "abc-2",
      "qty": 1,
      "name": "Product two",
      "price": 54,
      "product_type": "simple",
      "quote_id": "e3e1fd447e0e315dd761942cf949ce5d"
    }
]

Now I want get the images of each products in the list(Possibily a thumbnail image). Is there any way to achieve this result?

  • hi @ arun ss let me know whether u got solution for this question ? – NIPPU Aug 9 '17 at 11:29
3

On my point of view, you have two options

1/

Make other API calls :

  • /rest/V1/products/{sku}

OR

  • /rest/V1/products with search criteria params

You retrieve all product information included images such as :

<custom_attributes>
    <item>
        <attribute_code>thumbnail</attribute_code>
        <value>/m/b/mb01-blue-0.jpg</value>
    </item>
</custom_attributes>

2/

If you need the complete path of the image with Magento cache, you need to create or extend API.

You can based on this related post : Magento 2 Rest Api get Thumbnail Image url

0

From my experience I used the searchCriteria to get all products image paths using the sku of each product in the cart. It is done with just a single query for better performance, so there is just a single contact with the database. It is a better approach than making each call for each sku.

$productSearchUrl = "https://mobileapp.mymagento.com.ng/rest/V1/products?";

$max = sizeof($json['items']);

for ($i =0; $i < $max; $i++){

$value = $json['items'][$i]['sku'];
$productSearchUrl .= "searchCriteria[filter_groups][0][filters][$i][field]=sku".
    "&searchCriteria[filter_groups][0][filters][$i][value]=$value&".
    "searchCriteria[filter_groups][0][filters][$i][condition_type]=eq&";
}

$productSearchUrl=rtrim($productSearchUrl,"& ");
0

You cann use this link

http://yourmagentodomain.com/rest/V1/products/{SKU}/media

instead of

https://mobileapp.mymagento.com.ng/rest/V1/products?searchCriteria[filter_groups][0][filters][$i][field]=sku".
    "&searchCriteria[filter_groups][0][filters][$i][value]=$value&".
    "searchCriteria[filter_groups][0][filters][$i][condition_type]=eq&"

this big one.

  • After add this module show error in cmd - [Symfony\Component\Console\Exception\CommandNotFoundException] There are no commands defined in the "setup" namespace. – Gagan Jan 22 at 14:02
0

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/{{'cartId'}}/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;
    }
}
0

Please find below PHP script if you want to get product image data in the cart using "customer id".

<?php

use Magento\Framework\App\Bootstrap;

require '../../app/bootstrap.php'; // Change it as per your file location

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$quote = $objectManager->create('Magento\Quote\Model\Quote')->loadByCustomer($customer_id); // Change $customer_id as per your customer id
$quoteItems = $quote->getAllVisibleItems();
$result = array();
// get base url
$storeManager = $objectManager->get('Magento\Store\Model\StoreManagerInterface');
$base_url = $storeManager->getStore()->getBaseUrl();
$cutoff = explode("/", $base_url);
$burl = 'http://' . $cutoff[2];// Change it as per your base url
if (count($quoteItems) > 0) {
    foreach ($quoteItems as $oneItem) {
        $productData = $objectManager->get('Magento\Quote\Model\Quote\Item')->load($oneItem->getId());
        $pimages = array();
        $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productData->getProductId());
        $productimages = $product->getMediaGalleryImages();
        foreach ($productimages as $productimage) { 
            array_push($pimages, $productimage['url']);
        }
        $result[] = [
            'item_id' => $oneItem->getId(),
            'product_id' => $productData->getProductId(),
            'sku' => $oneItem->getSku(),
            'qty' => $oneItem->getQty(),
            'name' => $oneItem->getName(),
            'price' => $oneItem->getPrice(),
            'product_type' => $oneItem->getProductType(),
            'quote_id' => $oneItem->getQuoteId(),
            'image' => $pimages,
        ];
    }
}

json_encode($result);

?>

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.