How To

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

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

Click to rate this post!
[Total: 9 Average: 4.7]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

  • 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.

  • 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?

  • 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."}]}}

    • Please Verify you have implemented the blog properly and Please confirm that the field names are not mismatched at any place.

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

3 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

4 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

5 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

7 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago