Magento – Magento 2 Get Value of Custom Attribute on Magento 2 Rest API V1/orders/items

apimagento2restsales-order-item

I am trying to get the Custom Attribute I have in the sales_order_item to display on the rest/V1/orders/items API call. I was able to get the Attribute to display on the rest/V1/orders API call. Using a Magento\Sales\Api\OrderRepositoryInterface plugin. But the Attribute don't display on the rest/V1/orders/items API call. I was trying to use the OrderItemRepositoryInterface plugin, but I don't know what functions to add or if this is the correct way to do this.

Thanks.

Best Answer

You have to make your Custom Attribute attribute as extension attribute for Magento\Sales\Api\Data\OrderItemInterface

create extension_attributes.xml at your modules app/code/{Vendorname}/{ModuleName}/etc.

<?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\OrderItemInterface">
        <attribute code="{Your_Custom_Field}" type="string" />
    </extension_attributes>
</config>

I assume that your field as varchar that why I have add type as string type variable (type="string").

Update,

As you want to expose that rest/V1/orders/items Api point then you have to create a plugin on Magento\Sales\Model\Order\ProductOption::add()

Here the plugin Class:

<?php


namespace {VendorName}\{ModuleName}\Plungin;

use Magento\Sales\Api\Data\OrderItemInterface;

class ProductOption
{


    /**
     * @var \Magento\Sales\Api\Data\OrderItemExtensionFactory
     */
    private $orderItemExtensionFactory;

    public function __construct(
        \Magento\Sales\Api\Data\OrderItemExtensionFactory $orderItemExtensionFactory
    ) {

        $this->orderItemExtensionFactory = $orderItemExtensionFactory;
    }
    public function beforeAdd(
        \Magento\Sales\Model\Order\ProductOption $subject,
        OrderItemInterface $orderItem
    ) {
        $extensionAttributes = $orderItem->getExtensionAttributes();
        if(null=== $extensionAttributes){
            $extensionAttributes= $this->orderItemExtensionFactory->create();

        }
        $extensionAttributes->setCustomField($order->getCustomField());
        $orderItem->setExtensionAttributes($extensionAttributes);
    }
}
Related Topic