How to Get Value of Custom Attribute on Magento 2 Rest API

Magento 2 REST API is the best way of developing the cross-platform app to communicate with your Magento 2 stores. While developing an app, you would require to get value of custom attribute on Magento 2 REST API and use this further in the app. Today, I have come up with the complete guide to get value of custom attribute on Magento 2 REST API. Additionally, in Magento 2 get customer data from attribute value it becomes a crucial aspect in this context.

Steps to Get Value of Custom Attribute on Magento 2 Rest API:

Create/Add a new column in ‘sales_order‘ table and set value for the existing order.

Create a new file at app\code\Vendor\Module\etc\extension_attributes.xml and put the below code:

<?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\Sales\Api\Data\OrderInterface">
            <attribute code="custom_attribute" type="string" />
        </extension_attributes>
    </config>

Create event.xml at app\code\Vendor\Module\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="sales_order_load_after">
            <observer name="sales_order_load_custom_attribute" instance="Vendor\Module\Observer\Sales\OrderLoadAfter" />
        </event>
    </config>

Create OrderLoadAfter.php at app\code\Vendor\Module\Observer\Sales\OrderLoadAfter.php

<?php
namespace Vendor\Module\Observer\Sales;
use Magento\Framework\Event\ObserverInterface;
class OrderLoadAfter implements ObserverInterface
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $order = $observer->getOrder();
        $extensionAttributes = $order->getExtensionAttributes();
        if ($extensionAttributes === null) {
            $extensionAttributes = $this->getOrderExtensionDependency();
        }
        $attr = $order->getData('custom_attribute');
        $extensionAttributes->setCustomAttribute($attr);
        $order->setExtensionAttributes($extensionAttributes);
    }
    private function getOrderExtensionDependency()
    {
        $orderExtension = \Magento\Framework\App\ObjectManager::getInstance()->get(
            '\Magento\Sales\Api\Data\OrderExtension'
        );
        return $orderExtension;
    }
}

After getting an order on Magento 2 Rest API, you can see the custom attribute in the response.

That’s all about getting value of custom attribute on Magento 2 REST API. Let me know which custom attribute value did you get using the code above and how you used the value in your app. Also you can Magento 2 add category attribute to custom attribute group integrating a third-party API and using a category attribute!

Table of Contents