
While Magento 2 already has a proper documentation of their latest REST API collection, but we still have some requirements which needs some customization. Like- how to get all product details with stock using Magento 2 REST APIs?
Many of you may have already googled and probably found this API rest/V1/products?searchCriteria[page_size]=20 . But does this meets the requirements?
No. It returns all the related data but stock details.
“Magento2 does not suggest to add stock info to listing API a MSI add to 2.3 version.“
So, how do we get the stock details using Magento 2 REST APIs?
Let’s find out-
1.Create di.xml
at your app/code/Vendor/Module/etc
We are going to update
data of ExtensionPool
Magento\Catalog\Api\Data\ProductInterface
<?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\Module\Model\ReadHandler</item>
</item>
</item>
</argument>
</arguments>
</type>
</config>
2. Define ReadHandler class.
<?php
namespace Vendor\Module\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;
}
// echo "piddd-".$product->getId();
$stockItem =$this->stockRegistry->getStockItem($product->getId());
$extensionAttributes = $product->getExtensionAttributes();
// echo "<pre>";
// var_dump($extensionAttributes->getData());
// die;
$extensionAttributes->setStockItem($stockItem);
$product->getExtensionAttributes()->setStockItem($stockItem);
return $product;
}
}
That’s it.
Enable this module and start using your extended Magento 2 REST API. It should return the results like below image.
API endpoint: rest/V1/products?searchCriteria[page_size]=20
Response:

Nice ! Do you know how I could sort on, say, stockItem.qty ?