Magento, Magento 2

Magento 2 : Get Product Image URL in REST API

Magento 2 : Get Product Image URL in REST API

In this tutorial, I will explain to you how to get the product image URL in the REST API in Magento 2. When we need to get any product image URL programmatically at the front end side, we have many reference code for that and get easily output.

But, when we need to get the product image URL by SKU/id at that time, we face an issue like we get product image URL from the webapi_rest path. For eg :


http://127.0.0.1/m231/pub/static/webapi_rest/_view/en_US/Magento_Catalog/images/product/placeholder/.jpg

So, How we can solve this issue and get the product image URL from the cache or pub media folder?

For that, you need to add \Magento\Store\Model\App\Emulation class to start emulation with set front-end area code with appropriate store id. After, start emulation we can apply any logic code and then, we need to stop emulation. So, the question is how we apply these steps in our REST API?

You may like this :

Let’s start to create a module for how to get a product image URL using the REST API.

1) Firstly, Create registration.php file at app/code/Rh/CustomApi/ and paste the below code :


<?php
/**
 * Created By : Rohan Hapani
 */
use \Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Rh_CustomApi', __DIR__);

2) Create module.xml file at app/code/Rh/CustomApi/etc/ and paste the below code :


<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
   <module name="Rh_CustomApi" schema_version="1.0.0" setup_version="1.0.0" />
</config>

3) Create di.xml file at app/code/Rh/CustomApi/etc/ for API Interface file and paste the below code :


<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
   <preference for="Rh\CustomApi\Api\GetProductImage" type="Rh\CustomApi\Model\GetProductImageUrl" />
</config>

4) Create webapi.xml file at app/code/Rh/CustomApi/etc/ for the set router of API and paste the below code :


<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">
   <route url="/V1/getproductimage/:sku" method="GET">
      <service class="Rh\CustomApi\Api\GetProductImage" method="getProductImageUrl" />
      <resources>
         <resource ref="anonymous" />
      </resources>
   </route>
</routes>

5) Create GetProductImage.php file at app/code/Rh/CustomApi/Api/ to create the interface and paste the below code :


<?php
/**
 * Created By : Rohan Hapani
 */
namespace Rh\CustomApi\Api;

interface GetProductImage
{
    /**
     * @api
     * @param  string $sku
     * @return array
     */
    public function getProductImageUrl($sku);
}

6) At the last, Create GetProductImageUrl.php file at app/code/Rh/CustomApi/Model/ to create a model file and paste the below code :


<?php
/**
 * Created By : Rohan Hapani
 */

namespace Rh\CustomApi\Model;

use Rh\CustomApi\Api\GetProductImage;

class GetProductImageUrl implements GetProductImage
{
    /**
     * @var \Magento\Store\Model\App\Emulation
     */
    protected $appEmulation;

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

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

    /**
     * @var \Magento\Catalog\Helper\Image
     */
    protected $imageHelper;

    /**
     * @param \Magento\Store\Model\App\Emulation              $appEmulation
     * @param \Magento\Store\Model\StoreManagerInterface      $storeManager
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     * @param \Magento\Catalog\Helper\Image                   $imageHelper
     */
    public function __construct(
        \Magento\Store\Model\App\Emulation $appEmulation,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Catalog\Helper\Image $imageHelper
    ) {
        $this->appEmulation = $appEmulation;
        $this->storeManager = $storeManager;
        $this->productRepository = $productRepository;
        $this->imageHelper = $imageHelper;
    }

    public function getProductImageUrl($sku)
    {
        $storeId = $this->storeManager->getStore()->getId();
        $product = $this->productRepository->get($sku);

        $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
        if (!$product)
        {
            $response = [
                [
                    "code" => '301',
                    "message" => "SKU " . $productSku . " Not Found On Magento",
                ],
            ];
            return $response;
        }
        else
        {
            $image_url = $this->imageHelper->init($product, 'product_base_image')->getUrl();
            $response = [
                [
                    "product_image_url" => $image_url,
                ],
            ];
            return $response;
        }

        $this->appEmulation->stopEnvironmentEmulation();
    }
}

Now, Run this below commands for setup module :


php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c

Output :

Product Image URL by REST API Magento 2
Product Image URL by REST API Magento 2

I hope this blog will helpful for easily understand about how to get product image URL in REST API in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged , , ,