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

Node.js | HTTP Module

Node.js, known for its asynchronous and event-driven architecture, offers a multitude of built-in modules that…

2 days ago

Google’s August 2024 Core Update has Fully Rolled Out

Google has officially rolled out its much-anticipated August 2024 Core Update on August 15, 2024,…

3 days ago

Invoicing Guidelines for Independent E-Commerce Businesses

In e-commerce, it's important to understand that it's not just about running an online store.…

4 days ago

Building Dynamic Frontend Applications with Laravel and Alpine.js

In modern web development, building dynamic, interactive front-end applications is essential. Laravel, a powerful PHP…

4 days ago

Exploring Laravel 10’s New Query Builder Enhancements

Laravel, known for its elegant syntax and ease of use, has continually refined its core…

5 days ago

Magento 2 Extensions Digest August 2024 (New Release & Updates)

As we continue to innovate and enhance the Magento 2 ecosystem, August 2024 has been…

6 days ago