4

I am using Magento 2.1.6 CE and also am using default rest api's for create mobile app. When I get product by sku I get all the details of the particular product including custom attributes also.

But in custom attributes I have some attributes like color attribute (i.e. dropdown and filterable). I have various options for color attribute like Blue, Green, Red etc

When am requesting /V1/products/{{sku}} it shows custom attributes like following, (it shows option_id instead of option_value).

....
{
   "attribute_code": "color",
   "value": "11"
},
....

But I need this like the following,

....
{
   "attribute_code": "color",
   "value": "Green"
},
....

How can I get this done?

Please suggest me is there any default options available to done this.

  • 1
    hi @vignesh please confirm those attributes showing on product view page at moe information section? – Nagaraju K Aug 30 '17 at 5:44
  • 1
    Yes it's showing there correctly @NagarajuKasa – Vignesh Bala Aug 30 '17 at 5:46
  • whether you would like to implement new api from your custom module? ex:- rest/V1/product/sku – Nagaraju K Aug 30 '17 at 5:48
  • No am using default one only @NagarajuKasa – Vignesh Bala Aug 30 '17 at 6:00
  • hi @vignesh bala please check my answer and get back with u r doubts so that i will assist u thanks – Nagaraju K Aug 30 '17 at 8:19
9

Please follow the below steps from custom module if it success then you can customize whatever you want.

Note:- we are creating a new product attribute and associating the required data to the product attribute.

Step 1:- create a new module using silk software tool ex:- CompanyName_ModuleName

Step 2:- create a new product attribute using install script (or) admin end.

Step 3:- create a webapi.xml => /app/code/CompanyName/ModuleName/etc/webapi.xml

<?xml version="1.0" ?>
<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="CompanyName\ModuleName\Api\ProductsInterface" method="getAdditional"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Step 4: app/code/CompanyName/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="CompanyName\ModuleName\Api\ProductsInterface" type="CompanyName\ModuleName\Model\Products" />  
</config>

Step 5: app/code/CompanyName/ModuleName/Api/ProductsInterface.php

<?php

namespace CompanyName\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);

}

Step 6: app/code/CompanyName/ModuleName/Model/Products.php

 <?php
namespace CompanyName\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;
    }



}

Step 7: after did the changes make sure use di:compile

Step 8: open postman application for getting the result as shown below

Method: GET

UrL:- http://website.com/rest/V1/product/24-MB04

Step 9: Output enter image description here

| improve this answer | |
  • Okay I will check this one and let you know ASAP. Thanks ... – Vignesh Bala Aug 30 '17 at 9:40
  • thanks vignesh here i am customizing the entire api functionality from the custom module please get back with ur comments. – Nagaraju K Aug 30 '17 at 9:42
  • In your screen shot Activity attribute has 4 values, If am selected Gym only for product 24-MB04. How can I get that only ? – Vignesh Bala Aug 30 '17 at 9:45
  • you will get like this prnt.sc/geumys – Nagaraju K Aug 30 '17 at 9:48
  • So Activity is multiselect attribute. right ? – Vignesh Bala Aug 30 '17 at 9:53

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.