How to Get Product Image URL from REST API in Magento 2?

In today’s post, we are going to teach you how to get a product image URL from REST API in Magento 2.

This is useful in many different situations like when you’re developing a feature for images and need to retrieve the images URL.

Or, you can also use this tutorial when you’re migrating your Magento store and need to get all images URLs of your product images.

Whatever your requirement is, this easy-to-understand tutorial will definitely help you in getting product image URLs from REST API in Magento 2.

Now, usually when you try to get a product image URL by ID or SKU from REST API, you might face an issue from the webapi_rest path:

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

So the question is, how to overcome this issue and get a product image URL from the pub media folder or cache?

Well, in order to do that you will have to add \Magento\Store\Model\App\Emulation class for starting the emulation with set front-end area code along with appropriate store id.

After that, you will need to apply the logic code and then stop the emulation.

Also read: How to Fetch getUrl() in Plugin or Observer file in Magento 2?

Now, this is a time-consuming method. So, let’s figure out how to apply these steps directly in our REST API.

Steps to Get Product Image URL from REST API in Magento 2

Before we get started, you will need to create a simple module first.

For that, you can refer to our tutorial on How to Create a Simple Module in Magento 2.

Once you have created your module, it’s time to get started.

Step #1

First of all, we will have to create a registration.php file at app/code/Md/CustomApi/ and add the following code into the file.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
use \Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Md_CustomApi', __DIR__);

Step #2

Next, we will also have to create a module.xml file in app/code/Md/CustomApi/etc/ directory and add the following code into the file.

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, 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:Module/etc/module.xsd">
    <module name="Md_CustomApi" schema_version="1.0.0" setup_version="1.0.0"/>
</config>

Step #3

After that, we will need to create a di.xml file for API Interface in app/code/Md/CustomApi/etc/ directory and add the following code into the file.

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <preference for="Md\CustomApi\Api\GetProductImage" type="Md\CustomApi\Model\GetProductImageUrl" />
</config>

Step #4

Now, the next step is to create a webapi.xml file to set the router of API in app/code/Md/CustomApi/etc/ directory and add the following code into the file.

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<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="Md\CustomApi\Api\GetProductImage" method="getProductImageUrl"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Step #5

Now, we need to create a GetProductPage.php file to create the interface in the app/code/Md/CustomApi/Api/ directory and add the following code.

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Md\CustomApi\Api;
interface GetProductImage {
    /**
     * @api
     * @param string $sku
     * @return array
     */
    public function getProductImageUrl($sku);
}

Step #6

And lastly, we now need to create a GetProductImageUrl.php file to create a model file in app/code/Md/CustomApi/Model/ and add the following code.

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Md\CustomApi\Model;
use Md\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();
    }
}

And it’s done!

Now, we just need to execute the following commands to get the product image URL.

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

Once you execute these commands, you’ll see the output as shown below.

Also read: How to Manage Index and Cache Management Using Magento 2 REST API?

Conclusion

This is it! This is how you can get product image URL from REST API in Magento 2.

We hope that you found this Magento 2 tutorial helpful.

And if you need our professional assistance with Magento 2 Development Company, feel free to contact us.