0

I use the core API /V1/products/:sku to get the product using the SKU.

for example, I have 2 stores, one in English and another in Japanese. My API Endpoint is like http://local.mystore.com/storefront/en-us/rest/V1/products/myproduct for the English store and http://local.mystore.com/storefront/en-jp/rest/V1/products/myproduct for the Japanese.

For both the API I am getting the same labels (in English) for the attributes but In my Admin I have different labels for the attribute in the store scope level and its works fine in the Magento pages but not in the API.

enter image description here In this Function get() the $storeId is always null, I guess the problem is in this, if so please let me know How to send the store Id in this API to fix this issue.

enter image description here

2 Answers 2

0

I can see in your question, you are using the same store code(en-us) for both the mentioned endpoints or stores.

You have to replace the store code from English(en-us) with the Japanese store code(for example en-jp).

After replacing with the Japanese store code it looks like the below.

http://local.mystore.com/storefront/en-jp/rest/V1/products/myproduct

Now you have to call the store-wise API endpoint as below.

A] English store journey: If the customer doing a journey on English Store then call the below endpoint.

http://local.mystore.com/storefront/en-us/rest/V1/products/myproduct

A] Japanese store journey: If the customer doing a journey on a Japanese Store then call the below endpoint. Please note that replace the below store code with the actual your Japanese store code.

http://local.mystore.com/storefront/en-jp/rest/V1/products/myproduct

Check the below Magento Official Reference document showing usage of store code. enter image description here

4
  • Sorry for the wrong info, I’ve used the en-jp only at the code level, and while raising the question I typed the wrong endpoint. Now I've updated the question
    – Sathya
    Jan 17 at 11:08
  • Hey! FYI, I have multiple stores in our project & the below APIs giving store-wise results. for example UAE en : /rest/uae_en/V1/products/207360311 & UAE ar : /rest/uae_ar/V1/products/207360311. In my case, I have verified the product name in English & Arabic. Also, I have observed in your endpoints store code before the rest keyword. Jan 17 at 12:13
  • I have doubts about whether you are passing <store_code> in the endpoint or not. Because i assume that this is your domain name for Japanese store local.mystore.com/storefront/en-jp right ? Jan 17 at 12:17
  • For a better understanding see this example: /rest/<store_code>/V1/products/<SKU>. In my case uae_en & uae_ar is <store_code>. I hope these findings help you!!! Jan 17 at 12:24
0

1)create a xml file at path /app/code/VendorName/ModuleName/etc/webapi.xml

<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
<route url="/V1/product/:sku" method="GET">
        <service class="VendorName\ModuleName\Api\ProductsInterface" method="getAdditional"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

2)create app/code/VendorName/ModuleName/etc/di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="VendorName\ModuleName\Api\ProductsInterface" type="VendorName\ModuleName\Model\Products" />  
</config>

3)create app/code/VendorName/ModuleName/Api/ProductsInterface.php

<?php

namespace VendorName\ModuleName\Api;

interface ProductsInterface
{
     /**
     * Get info about product by product SKU
     *
     * @param string $sku
     * @param bool $editMode
     * @param int|null $storeId
     * @param bool $forceReload
     * @return \Magento\Catalog\Api\Data\ProductInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getAdditional($sku, $editMode = false, $storeId = null, $forceReload = false);
}

4)create app/code/VendorName/ModuleName/Model/Products.php

<?php
namespace VendorName\ModuleName\Model;
use Magento\Framework\Pricing\PriceCurrencyInterface;

class Products implements \Ewall\Mobileshop\Api\ProductsInterface
{
   /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;

    /**
     * @var Product[]
     */
    protected $instances = [];

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product
     */
    protected $resourceModel;

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

    /**
     * @var \Magento\Catalog\Helper\ImageFactory
     */
    protected $helperFactory;

    /**
     * @var \Magento\Store\Model\App\Emulation
     */
    protected $appEmulation;

    /**
     * Review model
     *
     * @var \Magento\Review\Model\ReviewFactory
     */
    protected $_reviewFactory;

     /**
     * Review resource model
     *
     * @var \Magento\Review\Model\ResourceModel\Review\CollectionFactory
     */
    protected $_reviewsColFactory;

    /**
     * @var PriceCurrencyInterface
     */
    protected $priceCurrency;

    /**
     * ProductRepository constructor.
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Catalog\Model\ResourceModel\Product $resourceModel
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param  \Magento\Review\Model\ReviewFactory $reviewFactory
     * @param  \Magento\Review\Model\ResourceModel\Review\CollectionFactory $collectionFactory
     * @param PriceCurrencyInterface $priceCurrency
     */
    public function __construct(
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\Product $resourceModel,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Store\Model\App\Emulation $appEmulation,
        \Magento\Catalog\Helper\ImageFactory $helperFactory,
        \Magento\Review\Model\ReviewFactory $reviewFactory,
        \Magento\Review\Model\ResourceModel\Review\CollectionFactory $collectionFactory,
        PriceCurrencyInterface $priceCurrency
    ) {
        $this->productFactory       =  $productFactory;
        $this->storeManager         =  $storeManager;
        $this->resourceModel        =  $resourceModel;
        $this->helperFactory        =  $helperFactory;
        $this->appEmulation         =  $appEmulation;
        $this->_reviewFactory       =  $reviewFactory;
        $this->_reviewsColFactory   =  $collectionFactory;
        $this->priceCurrency        =  $priceCurrency;

    }


    /**
     * {@inheritdoc}
     */
    public function getAdditional($sku, $editMode = false, $storeId = null, $forceReload = false)
    {
        $cacheKey = $this->getCacheKey([$editMode, $storeId]);
        if (!isset($this->instances[$sku][$cacheKey]) || $forceReload) {
            $product = $this->productFactory->create();

            $productId = $this->resourceModel->getIdBySku($sku);

            if (!$productId) {

                throw new NoSuchEntityException(__('Requested product doesn\'t exist'));
            }
            if ($editMode) {
                $product->setData('_edit_mode', true);
            }
            if ($storeId !== null) {
                $product->setData('store_id', $storeId);
            } else {

                $storeId = $this->storeManager->getStore()->getId();
            }
            $product->load($productId);

            //Custom Attributes Data Added here            
            $moreInformation = $this->getMoreInformation($product);                     
            $product->setCustomAttribute('more_information', $moreInformation);
            // Custom Attributes Data Ends here
            $this->instances[$sku][$cacheKey] = $product;
            $this->instancesById[$product->getId()][$cacheKey] = $product;          
        }

        return $this->instancesById[$product->getId()][$cacheKey];      

   }

    /**
     * Get key for cache
     *
     * @param array $data
     * @return string
     */

    protected function getCacheKey($data)
    {
        $serializeData = [];
        foreach ($data as $key => $value) {         

            if (is_object($value)) {
                $serializeData[$key] = $value->getId();             
            } else {                
                $serializeData[$key] = $value;              
            }
        }       
        return md5(serialize($serializeData));
    }

    /**
     * Get More information of the product
     * @param \Magento\Catalog\Model\Product $product
     * @return array
    */

    protected function getMoreInformation($product)
    {
        $data = [];
        $excludeAttr = [];
        $attributes = $product->getAttributes();
        foreach ($attributes as $attribute) {
            if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
                $value = $attribute->getFrontend()->getValue($product);

                if (!$product->hasData($attribute->getAttributeCode())) {
                    $value = __('N/A');
                } elseif ((string)$value == '') {
                    $value = __('No');
                } elseif ($attribute->getFrontendInput() == 'price' && is_string($value)) {
                    $value = $this->priceCurrency->convertAndFormat($value);
                }

                if (is_string($value) && strlen($value)) {
                    $data[$attribute->getAttributeCode()] = [
                        'label' => __($attribute->getStoreLabel()),
                        'value' => $value,
                        'code' => $attribute->getAttributeCode(),
                    ];
                }
            }
        }

        return $data;
}

5)Run command bin/magento setup:di:compile

6)In postman execute url BaseUrl/rest/V1/product/SKU-987

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.