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 Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 hour ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

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

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago