I have created custom rest api to create/update attribute options by attribute_id.
Here is my webapi.xml file code.
<route url="/V1/attribute/AttributeOption" method="POST">
<service class="Vendor\Module\Api\AttributeInterface" method="AttributeOption"/>
</route>
Api/AttributeInterface.php
<?php
namespace Vendor\Module\Api;
interface AttributeInterface
{
/**
* POST for attribute api
* @param mixed $param
* @return array
*/
public function AttributeOption($params);
}
Model/Attribute.php
<?php
namespace Vendor\Module\Model;
use Vendor\Module\Api\AttributeInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Store\Model\StoreManagerInterface;
class Attribute implements AttributeInterface
{
protected $_eavSetupFactory;
protected $_storeManager;
protected $_attributeFactory;
protected $eavAttributeFactory;
protected $attributeOptionManagement;
protected $productFactory;
private $productAttributeRepository;
protected $objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager,
\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ResourceModel\Eav\Attribute $attributeFactory,
\Magento\Eav\Model\Entity\AttributeFactory $eavAttributeFactory,
\Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository
) {
$this->_objectManager = $objectManager;
$this->_eavSetupFactory = $eavSetupFactory;
$this->_storeManager = $storeManager;
$this->_attributeFactory = $attributeFactory;
$this->eavAttributeFactory = $eavAttributeFactory;
$this->attributeOptionManagement = $attributeOptionManagement;
$this->productFactory = $productFactory;
$this->productAttributeRepository = $productAttributeRepository;
}
public function AttributeOption($params) {
// looking for logic to create / update options from request
}
}
Here is my json Request:
{
"params":{
"Type": "create",
"attribute_id" : "159",
"OptionValues": [
{
"OptionId": "01",
"OptionName": "Test"
},
{
"OptionId": "Null",
"OptionName" : "Test2"
}
]
}
}
I need to create the option for particular attribute by reading the above json,
if OptionId = null i need to create the new option otherwise
I need to update the label for option_id.
Can anyone help me with this please.