In Magento 2 every API depends on Interface and output of API depends on another interface
in vendor/magento/module-sales/Api/OrderRepositoryInterface.php you can see have a method get which return \Magento\Sales\Api\Data\OrderInterface when you open that file has a method getExtensionAttributes() if that method available then you can add your any attribute in API. So explain step by step
Step 1: You need to create a file in your custom module app/code/Auriga/Addon/etc/extension_attributes.xml (you can implement in your any module)
<?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="custom_attribute" type="string" />
</extension_attributes>
</config>
Step 2: need to create a file in app/code/Auriga/Addon/etc/webapi_rest/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Sales\Api\OrderRepositoryInterface">
<plugin name="orderInformationUpdate" type="Auriga\Addon\Plugin\Api\OrderRepository" />
</type>
</config>
Step 3:as declared in di.xml we need to create a file in OrderRepository.php in /var/www/html/choppingboard/app/code/Auriga/Addon/Plugin/Api/OrderRepository.php
<?php namespace Auriga\Addon\Plugin\Api; class OrderRepository {
public function __construct(\Auriga\Addon\Model\CartCalculation $cartCalculation) {
$this->cartCalculation = $cartCalculation;
}
public function afterGet(\Magento\Sales\Api\OrderRepositoryInterface $subject, $entity) {
$extensionAttributes = $entity->getExtensionAttributes ();
if ($extensionAttributes) {
$extensionAttributes->setCustomAttribute ( 'custom_value' );
$entity->setExtensionAttributes ( $extensionAttributes );
}
return $entity;
}}
Step 4 : need to run "php bin/magento setup:upgrade"
And you can check a customer_attribute node is avablible in result Now open BASE_URL/rest/default/V1/orders/2
