Add extension attribute in order data magento 2.

Magento 2 comes with a new design pattern called the service contracts. A service contract is a set of PHP interfaces used in a module. You can check an interface in any module API folder. Service contract includes service and data interfaces, which hide business logic details.

In Magento 2 You can add extension attributes for Order by creating an extension_attributes.xml file. Extension attributes are the persistent Attribute so you can’t find extension_attributes values in a database.

Let’s assume we need to add a new Order Comment field to order entity.

You need to use interface Magento\Sales\Api\Data\OrderInterface for add extension_attributes in Order entity. Thus, we need to define our order_comment extension attribute for the order extensible data object.
FilePath: app/code/Rbj/OrderComment/etc/extension_attributes.xml

Using above action we will define the additional setOrderComment( ) and getOrderComment( ) for auto-generated Magento\Sales\Api\Data\OrderExtension class.

We need to add the custom order_comment field value during the order data loaded. For this purpose, we need to create a plugin to get( ) and getList ( ) methods of order repository class. The plugin declaration is the following in global scope area,

File Path: app/code/Rbj/OrderFeedback/etc/di.xml

The afterGet and afterGetList methods will be called after the corresponding repository methods execution. So, this way we can affect the results:

Once the order entity is loaded, the Order Comment value will be added to the extension attributes data object.

Using the above way, You can get OrderComment field in any third party API service also.