Rest api to get product by sku with custom attribute option value in Magento 2.1
-
11-12-2020 - |
Domanda
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.
Soluzione
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
Altri suggerimenti
In lastest Magento 2 Versions Try this
/rest/V1/products/:sku