4

I am creating custom API in magento 2 and I need to get image URL of product.

I have used this code to get image URL:

$imageUrl = $this->listProductBlock->getImage($product,"category_page_grid")->getImageUrl();

Where $this->listProductBlock is the instance of \Magento\Catalog\Block\Product\ListProduct

With this I am getting url like this: ..static/version1574919158/webapi_rest/_view/en_US/Magento_Catalog/images/product/placeholder/.jpg

I have also tried imageBuilder class, but didn't work either.

Please help me solve this issue.

3

You just need to add App\Emulation instance in your model and define Area. In your case the area is AREA_FRONTEND.

 namespace YourPackage\YourModule\Model;

class YourApifilename implements \YourPackage\YourModule\Api\YourApiClassName
{
    protected $appEmulation;

    public function __construct(
        \Magento\Store\Model\App\Emulation $appEmulation
    )
    {

        $this->appEmulation = $appEmulation;

    }

    public Yourapimethod($param){

     $this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);

    /******** Do your work ******************/

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

I hope this will help

2
3

It is because you are currently in API area

You need to emulate your area to frontend. Just emulate, and after getting image you need to revert back emulation by stop emulate.

startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);

and

stopEnvironmentEmulation();

with Magento\Store\Model\App\Emulation instance

2
  • Your answer is also correct but you are late +1 for that Nov 28 '19 at 6:19
  • +1 on your efforts :) Dec 2 '19 at 11:04
2

You can use this one.

protected $_productRepositoryFactory;

public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
) {

    $this->_productRepositoryFactory = $productRepositoryFactory;
}

And you can get image like this way.

$product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
$product->getData('image');
$product->getData('thumbnail');
$product->getData('small_image');
3
  • I am getting product collection. It wont be good to load each product in loop, it would slow down my API. Thanks for the answer though Nov 28 '19 at 6:06
  • so you mean that you are working on whole product collection. I thought that you need only one product image path. Nov 28 '19 at 6:09
  • +1 on your efforts :) Dec 2 '19 at 11:04

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.