Magento 2 - Get product image url in API
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
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
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');