1.5 (30.83%) 72 votes

Here are the steps that you will follow to get value of custom attribute on Magento 2 Rest API in Magento 2 tutorial:
1. Create new column and set value for the existing order.
2. Create a specific new file.
3. Create an observe.
4. Create a file to handle the event.
5. Delete folder to apply function.

In this post, I will guide you how to get value of a custom attribute on the Magento 2 Rest API. 

Step 1:

I created a new column in table sales_order with name ‘tip_and_trick_attribute’ and set value for the existing orders. This is a custom attribute which I will get in this post.

Step 2:

I created a file \app\code\Magestore\TipAndTrick\etc\extension_attributes.xml in my extension folder with content below:

 

magento 2 rest api

Because Magento 2 doesn’t accept to add a new field in the response on the Rest API so I must create file extension_attributes.xml to add my custom attribute intoc.

Step 3:

I created an observe for event ‘sales_order_load_after’ through the file \app\code\Magestore\TipAndTrick\etc\events.xml to add my custom attribute into extension_attributes.xml.

 

magento 2 rest api

 

Step 4:

I created a file app\code\Magestore\TipAndTrick\Observer\Sales\OrderLoadAfter.php to handle the event ‘sales_order_load_after’ which I declared above.

 

 

magento 2 rest api

In execute function, I get my custom attribute from order data and set it into extension attributes of the orders.

Step 5 :

You must delete var\genaration folder to apply function ‘setTipAndTrickAttribute’ and getTipAndTrickAttribute’  in file ‘var\generation\Magento\Sales\Api\Data\OrderExtension.php’. This file will be created automatically.

magento 2 rest api

Step 6:

When I get order on Magento 2 Rest API, I saw my custom attribute in the response.

magento 2 rest api

 

Thank you!

You may want to try the Magento 2 Demo to fully experience its new awesome features. And of course, please feel free to find more Magento 2 Tutorials by our Experts.

Your Magento website needs a powerful Magento ERP for stock control.

DON'T MISS THE CHANCE!

magento erp

How to create an event in Magento 2? - Magento 2 events (Magento 2.3)
How to Setup Cron Job in Magento 2? (Magento 2.3)

Leave a Reply

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