3

Could anyone help me to find the rest api to get hex or image of visual swatch attribute?

I need the api to return the following, Label Value HEX or Image of the swatch.

Thanks

3
  • Do you mean as an EX : return colors in hex ?
    – Jsparo30
    Commented Mar 6, 2018 at 7:50
  • @Jsparo30 yes bro, i mean that.. i need hex colors to return in REST API, could you please help?
    – Medomage
    Commented Mar 8, 2018 at 10:13
  • I replied below.
    – Jsparo30
    Commented Mar 8, 2018 at 12:00

2 Answers 2

2

Unfortunatly I didn't find any API to get hex or image of visual swatch attribute. After playing a bit i write a module which use extension attribute for AttributeInterface.... I've tried with AttributeOptionInterface but without success.

After the module is installed is possible to fetch hex or image by checking the extension_attributes for these API calls:

http://domain.com/index.php/rest/V1/products/attributes?searchCriteria[filter_groups][0][filters][0][field]=attribute_code&searchCriteria[filter_groups][0][filters][0][value]=color
http://domain.com/index.php/rest/V1/products/attributes/93/

Tested with Magento 2.3.2

app/code/ProjectName/ModuleName/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'ProjectName_ModuleName',
    __DIR__
);

app/code/ProjectName/ModuleName/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="ProjectName_ModuleName" setup_version="1.0.0">
    </module>
</config>

app/code/ProjectName/ModuleName/etc/extension_attributes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
  <extension_attributes for="Magento\Eav\Api\Data\AttributeInterface">
      <attribute code="product_attribute_option_swatch" type="ProjectName\ModuleName\Api\Data\AttributeSwatchOptionInterface[]" />
  </extension_attributes>
</config>

Create AttributeSwatchOptionInterface and Model

app/code/ProjectName/ModuleName/Api/Data/AttributeSwatchOptionInterface.php

<?php
namespace ProjectName\ModuleName\Api\Data;

use Magento\Eav\Api\Data\AttributeOptionInterface;

interface AttributeSwatchOptionInterface extends AttributeOptionInterface
{
    /**
     * Constants used as data array keys
     */
    const TYPE = 'type';
    const SWATCHVALUE = 'swatch_value';
    /**
     * Get option label
     *
     * @return string
     */
    public function getType();
    /**
     * Set option label
     *
     * @param string $label
     * @return $this
     */
    public function setType($type);
    /**
     * Get option value
     *
     * @return string
     */
    public function getSwatchValue();
    /**
     * Set option value
     *
     * @param string $value
     * @return string
     */
    public function setSwatchValue($swatch_value);
}

app/code/ProjectName/ModuleName/Model/AttributeSwatchOption.php

<?php
namespace ProjectName\ModuleName\Model;

use ProjectName\ModuleName\Api\Data\AttributeSwatchOptionInterface;
use Magento\Eav\Model\Entity\Attribute\Option;

class AttributeSwatchOption extends Option implements AttributeSwatchOptionInterface
{
    /**
     * Resource initialization
     *
     * @return void
     */
    public function _construct()
    {
        parent::__construct();
    }

    public function getType()
    {
        return $this->getData(AttributeSwatchOptionInterface::TYPE);
    }

    public function getSwatchValue()
    {
        return $this->getData(AttributeSwatchOptionInterface::SWATCHVALUE);
    }

    public function setType($type)
    {
        return $this->setData(AttributeSwatchOptionInterface::TYPE, $type);
    }

    public function setSwatchValue($value)
    {
        return $this->setData(AttributeSwatchOptionInterface::SWATCHVALUE, $swatch_value);
    }   
}   

Now we add an observe for event catalog_entity_attribute_load_after

app/code/ProjectName/ModuleName/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="catalog_entity_attribute_load_after">
      <observer name="projectname_product_attribute_option_swatch" instance="ProjectName\ModuleName\Observer\OptionSwatchLoadAfter" />
  </event>
</config>

app/code/ProjectName/ModuleName/Observer/OptionSwatchLoadAfter.php

<?php
namespace ProjectName\ModuleName\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;

use Psr\Log\LoggerInterface as Logger;
use Magento\Swatches\Helper\Data as SwatchHelper;
use Magento\Eav\Api\Data\AttributeInterface;

class OptionSwatchLoadAfter implements ObserverInterface
{
    /**
     * @var Logger
     */
    protected $_logger;

    protected $_swatchHelper;

    public function __construct(Logger $logger, SwatchHelper $swatchHelper)
    {
        $this->_logger = $logger;
        $this->_swatchHelper = $swatchHelper;
    }
    /**
     * @param EventObserver $observer
     * @return $this
     * @throws \Exception
     */
    public function execute(EventObserver $observer)
    {
        $attribute = $observer->getEvent()->getData('attribute');

        $extensionAttributes = $attribute->getExtensionAttributes();

        //isVisualSwatch
        if ($this->_swatchHelper->isVisualSwatch($attribute))
        {
            $options = $attribute->getOptions();
            $options = $this->processOptions($options);

            $extensionAttributes->setProductAttributeOptionSwatch($options);
            $attribute->setExtensionAttributes($extensionAttributes);
        }

        return $this;
    }
    private function processOptions($options)
    {
        $option_ids = array();
        foreach($options as $option)
        {
            $option_ids[] = $option->getValue();
        }

        $swatches = $this->_swatchHelper->getSwatchesByOptionsId($option_ids);

        if (count($swatches) > 0)
        {
            foreach($options as $option)
            {
                if (isset($swatches[$option->getValue()]))
                {
                    $swatch = $swatches[$option->getValue()];
                    $option->setType($swatch['type']);
                    $option->setSwatchValue($swatch['value']);
                }
            }
        }

        return $options;
    }
}
1
  • This is what I'm looking for... Commented Feb 16, 2021 at 15:40
1

In Backend you should enter the hex values for your store colors in color attribute from :

Admin->Stores->Product then choose color ttributes Like

enter image description here

After that, call the Color Attribute API :

http://domain.com/index.php/rest/V1/products/attributes/93/options

enter image description here

Hope this help..

3
  • what about images? I think best would to alter API response
    – nikunj
    Commented Jun 11, 2018 at 17:45
  • I want swatch selected color. Commented Nov 27, 2018 at 9:34
  • this screenshot helped me. thank you Commented Oct 27, 2020 at 8:21

Your Answer

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

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