Add a Custom Order Attribute to API Response

Does your custom attribute is missing from the order api response? Let's check it together how you can include it in the response!

First of all let's create an order attribute called magevision_comment like below.

As is well know Magento 2 has introduced the Service Contracts design pattern which simply is a set of php interfaces. Checking the OrderInterface under Magento\Sales\Api\Data\OrderInterface we will see the service interface defined for the Order Service Contract. Checking the Data OrderInterface under Magento\Sales\Api\Data\OrderInterface we will see the data service interface for the Order Service. In the Data Order Interface we will see a lot of getters and setters but not for our customer attribute. Although there is the getter getExtensionAttributes and the setter setExtensionAttributes which are the ones that help use to extend the interface adding our new attribute. So let's declare our custom magevision_comment attribute as extension attribute. We can do this in the responsible configuration xml file called extension_attributes.xml like below.

So then, the next thing is to add our custom attribute to the order data loading. The best way to do that is to add a plugin for get and getList methods of order repository class.

Declaring our plugin

Create our plugin

Now by calling the rest API endpoint to get the order info '/V1/orders/{order_id}', we will get back also in the response the value of our custom attribute magevision_comment.

The full example as extension can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!

DigitalOcean Referral Badge