Extension Attributes in Magento 2

What are Extension Attributes?

Extension Attributes in Magento 2 allow developers to extend existing Service Contract data interfaces without modifying the core code. They provide a way to add additional data to entities such as Product, Customer, Order, Quote, etc.

This mechanism is part of Magento's Service Contract architecture and ensures that customizations remain upgrade-safe while still allowing modules to extend core data objects.

Extension attributes are commonly used in APIs (REST & GraphQL), repositories, and data interfaces.

Why Use Extension Attributes?

  • Add custom data to core entities without modifying core classes.
  • Maintain backward compatibility with Magento upgrades.
  • Expose additional fields in REST and GraphQL APIs.
  • Integrate third-party modules with existing Magento entities.

Key Files Required

To implement extension attributes, Magento uses the following files:

  • extension_attributes.xml → Defines new attributes.
  • Data Interface → Automatically generated by Magento.
  • Plugin or Repository Logic → Used to populate attribute values.

Step 1: Create extension_attributes.xml

This file defines which entity interface will receive new extension attributes.

(File: app/code/VendorName/ModuleName/etc/extension_attributes.xml)




This configuration adds a new extension attribute called custom_message to the Product entity.

Step 2: Access Extension Attributes in Code

Magento automatically generates the getter and setter methods for extension attributes.




This code retrieves the product's extension attributes and sets a custom value.

Step 3: Populate Extension Attributes Using Plugin

Often extension attributes need to be populated when loading data from a repository.

(File: app/code/VendorName/ModuleName/etc/di.xml)




Step 4: Create Plugin to Set Extension Attribute Value

(File: app/code/VendorName/ModuleName/Plugin/ProductRepositoryPlugin.php)




Generated Code

After running the Magento compilation command, Magento generates the extension interface:




Magento automatically generates:

  • ProductExtensionInterface
  • ProductExtension
  • Getter and setter methods

Best Practices for Extension Attributes

  • Always use extension attributes with Service Contracts.
  • Populate extension attributes using plugins on repositories.
  • Avoid direct model modification.
  • Use them for API-related data extensions.
  • Keep extension attributes lightweight to avoid performance issues.