I have added stock_item
in Category List Product details Rest API. Update ExtensionPool data of Magento\Catalog\Api\Data\ProductInterface
and add stock_item
data provider.
File path: magento\app\code\Vendor\StockitemApi\registration.php
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use \Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_StockitemApi', __DIR__);
File path: magento\app\code\Vendor\StockitemApi\etc\module.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Vendor_StockitemApi" >
</module>
</config>
File path: magento\app\code\Vendor\StockitemApi\etc\di.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\EntityManager\Operation\ExtensionPool">
<arguments>
<argument name="extensionActions" xsi:type="array">
<item name="Magento\Catalog\Api\Data\ProductInterface" xsi:type="array">
<item name="read" xsi:type="array">
<item name="stock_item" xsi:type="string">Vendor\StockitemApi\Model\ReadHandler</item>
</item>
</item>
</argument>
</arguments>
</type>
</config>
File path: magento\app\code\Vendor\StockitemApi\Model\ReadHandler.php
<?php
namespace Vendor\StockitemApi\Model;
class ReadHandler implements \Magento\Framework\EntityManager\Operation\ExtensionInterface
{
/**
* @var \Magento\CatalogInventory\Api\StockRegistryInterface
*/
private $stockRegistry;
public function __construct(
\Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
) {
$this->stockRegistry = $stockRegistry;
}
/**
* Magento\CatalogInventory\Api\Data\StockItemInterface
* @param type $product
* @param type $arguments
*/
public function execute($product, $arguments = [])
{
if ($product->getExtensionAttributes()->getStockItem() !== null) {
return $product;
}
$stockItem =$this->stockRegistry->getStockItem($product->getId());
$extensionAttributes = $product->getExtensionAttributes();
$extensionAttributes->setStockItem($stockItem);
$product->setExtensionAttributes($extensionAttributes);
return $product;
}
}