Extension Attributes in Magento 2 API

How to Create and Use Extension Attributes in Magento 2 API by Kiwi Commerce

Magento 2 extension attributes offer a flexible way to extend core and custom entities without changing their original classes. These attributes are especially useful when working with APIs, enabling additional data to be added to API responses or set via API requests. In this guide, we will walk you through how to create an extension attribute and use it within Magento 2 APIs using the Kiwi_ExtensionAttribute module.


What Are Extension Attributes?

Extension attributes are extra fields that can be added to entities such as products, orders, and customers in Magento 2. Unlike traditional EAV attributes, extension attributes do not automatically store data in the database. Instead, they are dynamically retrieved through plugins or data providers when needed.


Step-by-Step Guide to Creating an Extension Attribute in Magento 2 API

Step 1: Define the Extension Attribute
Start by creating the extension_attributes.xml file to declare the new attribute for the Magento product entity.

📂 app/code/Kiwi/ExtensionAttribute/etc/extension_attributes.xml

<?xml version=”1.0″?>

<extension_attributes xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Api/etc/extension_attributes.xsd”>

    <extension_attribute for=”Magento\Catalog\Api\Data\ProductInterface” code=”custom_attribute”>

        <type>string</type>

    </extension_attribute>

</extension_attributes>


Step 2: Create a Data Interface
Define the getter and setter methods for the new extension attribute.

📂 app/code/Kiwi/ExtensionAttribute/Api/Data/CustomAttributeInterface.php

<?php

namespace Kiwi\ExtensionAttribute\Api\Data;

interface CustomAttributeInterface

{

    public function getCustomAttribute();

    public function setCustomAttribute($customAttribute);

}


Step 3: Create the API Repository
Implement the repository that handles retrieving and setting the extension attribute.

📂 app/code/Kiwi/ExtensionAttribute/Model/CustomAttributeRepository.php

<?php

namespace Kiwi\ExtensionAttribute\Model;

use Kiwi\ExtensionAttribute\Api\CustomAttributeRepositoryInterface;

use Magento\Catalog\Api\ProductRepositoryInterface;

use Magento\Catalog\Api\Data\ProductExtensionFactory;

class CustomAttributeRepository implements CustomAttributeRepositoryInterface

{

    protected $productRepository;

    protected $productExtensionFactory;

    public function __construct(

        ProductRepositoryInterface $productRepository,

        ProductExtensionFactory $productExtensionFactory

    ) {

        $this->productRepository = $productRepository;

        $this->productExtensionFactory = $productExtensionFactory;

    }

    public function getCustomAttribute($sku)

    {

        $product = $this->productRepository->get($sku);

        $extensionAttributes = $product->getExtensionAttributes();

        return $extensionAttributes ? $extensionAttributes->getCustomAttribute() : null;

    }

    public function setCustomAttribute($sku, $value)

    {

        $product = $this->productRepository->get($sku);

        $extensionAttributes = $product->getExtensionAttributes() ?: $this->productExtensionFactory->create();

        $extensionAttributes->setCustomAttribute($value);

        $product->setExtensionAttributes($extensionAttributes);

        $this->productRepository->save($product);

        return $product;

    }

}


Step 4: Register the API Routes
Define the endpoints for getting and setting the custom attribute.

📂 app/code/Kiwi/ExtensionAttribute/etc/webapi.xml

<?xml version=”1.0″?>

<routes xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Webapi/etc/webapi.xsd”>

    <route url=”/V1/products/:sku/custom-attribute” method=”GET”>

        <service class=”Kiwi\ExtensionAttribute\Api\CustomAttributeRepositoryInterface” method=”getCustomAttribute”/>

        <resources>

            <resource ref=”Magento_Catalog::products” />

        </resources>

    </route>

    <route url=”/V1/products/:sku/custom-attribute” method=”POST”>

        <service class=”Kiwi\ExtensionAttribute\Api\CustomAttributeRepositoryInterface” method=”setCustomAttribute”/>

        <resources>

            <resource ref=”Magento_Catalog::products” />

        </resources>

        <data>

            <parameter name=”sku” force=”true”>%sku</parameter>

            <parameter name=”value” xsi:type=”string” force=”true”/>

        </data>

    </route>

</routes>


Step 5: Implement the Plugin to Inject the Attribute
A plugin is used to inject the attribute value into API responses dynamically.

📂 app/code/Kiwi/ExtensionAttribute/Plugin/ProductExtension.php

<?php

namespace Kiwi\ExtensionAttribute\Plugin;

use Magento\Catalog\Api\Data\ProductInterface;

use Magento\Catalog\Api\Data\ProductExtensionFactory;

use Magento\Catalog\Api\ProductRepositoryInterface;

class ProductExtension

{

    protected $productExtensionFactory;

    public function __construct(ProductExtensionFactory $productExtensionFactory)

    {

        $this->productExtensionFactory = $productExtensionFactory;

    }

    public function afterGetById(ProductRepositoryInterface $subject, ProductInterface $product)

    {

        $extensionAttributes = $product->getExtensionAttributes() ?: $this->productExtensionFactory->create();

        $extensionAttributes->setCustomAttribute(‘Custom Value’);

        $product->setExtensionAttributes($extensionAttributes);

        return $product;

    }

}


Step 6: Test the API
Now, test the created API to get and set the custom attribute.

Get Custom Attribute

curl -X GET “https://yourstore.com/rest/V1/products/sample-sku/custom-attribute”

Response:

{

    “custom_attribute”: “Custom Value”

}

Set Custom Attribute

curl -X POST “https://yourstore.com/rest/V1/products/sample-sku/custom-attribute” \

-H “Content-Type: application/json” \

–data ‘{“value”:”New Custom Value”}’

Response:

{

    “custom_attribute”: “New Custom Value”

}


Conclusion

Magento 2’s extension attributes offer a powerful way to extend your entities dynamically without modifying core files. With this guide, you’ve successfully:

  • Defined a new extension attribute.
  • Created an API to retrieve and set the attribute.
  • Implemented a plugin to inject the attribute values into API responses.
  • Tested your API to ensure everything works as expected.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *