In Magento 2, Extension Attributes are a way to add custom fields or data to existing service contracts (like APIs, models, repositories) without directly modifying the core code.

They’re especially used when you want your custom data to be accessible through Magento’s Web APIs (REST/SOAP) or service contracts.

Key Points About Extension Attributes

When to Use

Steps to Create an Extension Attribute

1. Create a Custom Table (optional)

If you need to store additional data:

CREATE TABLE custom_order_delivery_date (
entity_id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
delivery_date DATETIME NULL,
FOREIGN KEY (order_id) REFERENCES sales_order(entity_id)
);

2. Define extension_attributes.xml

Create file:

app/code/Vendor/Module/etc/extension_attributes.xml

<?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="delivery_date" type="string" />
</extension_attributes>
</config>

3. Create Extension Attribute Getter/Setter

Magento automatically generates these methods:

$order->getExtensionAttributes()->getDeliveryDate();

$order->getExtensionAttributes()->setDeliveryDate('2025-09-01');

4. Load & Save Attribute Data

You need a plugin or observer to fetch/save the data from your custom table:

public function afterGet(\Magento\Sales\Api\OrderRepositoryInterface $subject, $order)
{
$extensionAttributes = $order->getExtensionAttributes();
if ($extensionAttributes === null) {
$extensionAttributes = $this->extensionAttributesFactory->create(\Magento\Sales\Api\Data\OrderInterface::class);
}
$deliveryDate = $this->customOrderRepository->getDeliveryDateByOrderId($order->getEntityId());
$extensionAttributes->setDeliveryDate($deliveryDate);
$order->setExtensionAttributes($extensionAttributes);
return $order;
}

This ensures the data shows up in APIs.

5. Check in API Response

After clearing cache and running bin/magento setup:upgrade,

GET /V1/orders/:id will now return:

{
"entity_id": 1,
"increment_id": "000000001",
"extension_attributes": {
"delivery_date": "2025-09-01"
}
}