Magento – Adding new order field to API response: /V1/orders/:id without using extension_attributes

apimagento2restsoapweb services

So basically I want to extend the existing web-service /V1/orders/:id for adding new order field (say: erp_id).
It's a field in sales_order table and it's available when you load the $order object.

My main concern here is not to use the extension_attributes node for adding this new field. I want it to be on the same level as other standard fields.
The reason behind this is we already have many third parties relying on this structure.

So far gathered the key files for extension seems to be:

  • Magento\Sales\Api\OrderRepositoryInterface (service interface for the API)
  • Magento\Sales\Api\Data\OrderInterface (data interface for the API result)
  • Magento\Sales\Model\OrderRepository (concrete class for service interface)
  • Magento\Sales\Model\Order (concret class for data interface – esp. getters and setters)

Some similar queries waiting for an answer:

== EDIT ==
If you edit as below, you can have the custom field on the top-level in the SOAP response.

File: app/code/Magento/Sales/Api/Data/OrderInterface.php

//...
/*
 * ERP ID
 */
const ERP_ID = 'erp_id'; 
//...
/**
 * Gets the ERP Id
 *
 * @return int
 */
public function getErpId();

/**
 * Sets the ERP Id
 *
 * @param int $id
 * @return $this
 */
public function setErpId($id);

File: app/code/Magento/Sales/Model/Order.php

/**
 * {@inheritdoc}
 */
public function getErpId()
{
    return $this->getData(OrderInterface::ERP_ID);
}


/**
 * {@inheritdoc}
 */
public function setErpId($id)
{
    return $this->setData(OrderInterface::ERP_ID, $id);
}

It's that simple logically. But the problem here is overriding the interface.

Another Question:
is this possible in Magento 2 <preference for="Magento\Sales\Api\Data\OrderInterface" type="My\Custom\Api\Data\OrderInterface" />
(i.e. overriding of one interface by another)

Best Answer

The intended mechanism by which to add attributes to existing models is via the extension_attributes mechanism. It take some work to set up, but this exposes the data consistently throughout the API (both internally, for code hinting, etc., and externally, for SOAP and REST).

To my knowledge, there is no mechanism for adding top-level attributes to the API, nor is there supposed to be.

Rewriting a variety of core classes to accomplish this would be highly invasive and likely to conflict with other plugins trying to do the same. It would also be a complete dismissal of Magento 2's conventions and best practices.

There are a variety of resources on working with Extension Attributes:

http://devdocs.magento.com/guides/v2.0/extension-dev-guide/attributes.html
How do the extension attributes work in Magento 2?
How to use extension_attributes in Magento2

Related Topic