Magento 2: How to Get Order Details with Custom Extension Attributes using REST API

How to Get Order Details with Custom extension attributes using REST API Magento 2

Hello Magento Friends,

I hope all are doing great. Today I will be explaining Magento 2: How to Get Order Details with Custom Extension Attributes using REST API. In case you missed reviewing our previous blog, How to Get Region Code by Region ID in Magento 2.

Introduction:

When customers purchase products, Magento 2 handles various entities, like products, customers, and orders. Magento provides different ways to fetch that entity data. One of them is to Get Order Details using REST API in Magento 2.

But suppose we have used some custom extension attributes with orders or products or customers. In that case, Magento default does not return that custom extension attributes values while we get details using the REST API.

No worries! With the below code’s help, we will learn How to Get Order Details with Custom Extension Attributes using REST API. So let us get started.

Steps to Get Order Details with Custom Extension Attributes using REST API in Magento 2:

Step 1: Create extension_attributes.xml file inside app\code\Vendor\Extension\etc folder and add the code as mentioned below:

<?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="delivery_charge" type="decimal" />
		<attribute code="payment_charge" type="decimal"/>
	</extension_attributes>
</config>

Step 2: Next create events.xml file inside app\code\Vendor\Extension\etc folder and add the below code:

<?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_attribute" instance="Vendor\Extension\Observer\OrderLoadAfter"/>
    </event>
</config>

Step 3: Next create OrderloadAfter.php file inside app\code\Vendor\Extension\Observer folder and add the below-mentioned code:

<?php
namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;

class OrderLoadAfter implements ObserverInterface
{
    protected $_orderExtension;

    public function __construct(\Magento\Sales\Api\Data\OrderExtension $orderExtension)
    {
        $this->_orderExtension = $orderExtension;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
            $order = $observer->getOrder();

            $extensionAttributes= $order->getExtensionAttributes();
            if ($extensionAttributes === null)
            {
                $extensionAttributes = $this->_orderExtension;
            }
            $deliverycharge = $order->getData('delivery_charge');
            $paymentcharge = $order->getData('payment_charge');
         
            $extensionAttributes->setData('delivery_charge',$deliverycharge);
            $extensionAttributes->setData('payment_charge',$paymentcharge);
           
            $order->setExtensionAttributes($extensionAttributes);
    }
}

Step 4: Next clear the generated folder from Magento root and clear cache.

Step 5: Finally, execute the getOrderDetails.php script file inside your Magento root folder and add the below code. (You can use this code in your Magento file system. e.g., you can even use it in your custom module).

<?php
$userData = array("username" => "admin", "password" => "adminPassword");
$baseUrl = "http://domain.com/index.php"; // your magento base url
$ch = curl_init($baseUrl."/rest/V1/integration/admin/token");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

$token = curl_exec($ch);

$ch = curl_init($baseUrl."/rest/V1/orders/1");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));

$result = curl_exec($ch);

$result = json_decode($result, 1);
echo '<pre>';print_r($result);?>

That’s it!

Conclusion:

Accordingly, you can Get Order Details with Custom Extension Attributes using REST API in Magento 2.Mention your difficulties in the comment part. I will be happy to solve it.

Keep Learning! Stay informed!

Happy Coding

Previous Article

How to Get Region Code by Region ID in Magento 2

Next Article

How to Upload Product Image Placeholder in Magento 2

Write a Comment
  1. I am getting the below error while calling API using postman. Any idea?

    Fatal error: Uncaught Error: Call to undefined method
    SimplifiedMagento\Database\Api\Data\AffiliateMemberExtension::setCode() in
    /var/www/html/magento2/app/code/SimplifiedMagento/Attribute/Model/Plugin/CodeAttributeExtension.php:35
    Stack trace:
    #0 /var/www/html/magento2/vendor/magento/framework/Interception/Interceptor.php(135):
    SimplifiedMagento\Attribute\Model\Plugin\CodeAttributeExtension->aroundGetAffiliateMemberById(Object(SimplifiedMagento\Database\Model\AffiliateMemberRepository\Interceptor),
    Object(Closure), 9)
    #1 /var/www/html/magento2/vendor/magento/framework/Interception/Interceptor.php(153):
    SimplifiedMagento\Database\Model\AffiliateMemberRepository\Interceptor->Magento\Framework\Interception\{closure}(9)
    #2 /var/www/html/magento2/generated/code/SimplifiedMagento/Database/Model/AffiliateMemberRepository/Interceptor.php(26):
    SimplifiedMagento\Database\Model\AffiliateMemberRepository\Interceptor->___callPlugins(‘getAffiliateMem…’, Array,
    NULL)
    #3 [internal function]: SimplifiedMagento\Database\Model\AffiliateM in
    /var/www/html/magento2/app/code/SimplifiedMagento/Attribute/Model/Plugin/CodeAttributeExtension.php on line
    35
    {“messages”:{“error”:[{“code”:500,”message”:”Fatal Error: ‘Uncaught Error: Call to undefined method SimplifiedMagento\\Database\\Api\\Data\\AffiliateMemberExtension::setCode() in \/var\/www\/html\/magento2\/app\/code\/SimplifiedMagento\/Attribute\/Model\/Plugin\/CodeAttributeExtension.php:35\nStack trace:\n#0 \/var\/www\/html\/magento2\/vendor\/magento\/framework\/Interception\/Interceptor.php(135): SimplifiedMagento\\Attribute\\Model\\Plugin\\CodeAttributeExtension->aroundGetAffiliateMemberById(Object(SimplifiedMagento\\Database\\Model\\AffiliateMemberRepository\\Interceptor), Object(Closure), 9)\n#1 \/var\/www\/html\/magento2\/vendor\/magento\/framework\/Interception\/Interceptor.php(153): SimplifiedMagento\\Database\\Model\\AffiliateMemberRepository\\Interceptor->Magento\\Framework\\Interception\\{closure}(9)\n#2 \/var\/www\/html\/magento2\/generated\/code\/SimplifiedMagento\/Database\/Model\/AffiliateMemberRepository\/Interceptor.php(26): SimplifiedMagento\\Database\\Model\\AffiliateMemberRepository\\Interceptor->___callPlugins(‘getAffiliateMem…’, Array, NULL)\n#3 [internal function]: SimplifiedMagento\\Database\\Model\\AffiliateM’ in ‘\/var\/www\/html\/magento2\/app\/code\/SimplifiedMagento\/Attribute\/Model\/Plugin\/CodeAttributeExtension.php’ on line 35″,”trace”:”Trace is not available.”}]}}

  2. I added a custom product attribute via code, and implemented the above solution, but the custom attribute is NOT visible in the API response.

    How do I get a custom product attribute to show in the order API?

  3. Nilesh Patel

    I want to display order attribute value outside ‘extension_attributes’ level.. it means display order attribute value at the top level of order rest API response.

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨