Exclude Out of stock products in magento2 rest api for products

Hello Friends

In Today’s Topic I am going to cover how you can exclude out of stock products in magento2’s product rest api.
There is an issue with magento2 rest api they are not excluding out of stock products in their rest api for products , So I am adding a solution here to fix this.
Create your Module like
MageAcademy/Catalog
create di.xml and put below code
<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
   
    <type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
        <plugin name="instockFilter" type="MageAcademy\Catalog\Plugin\Catalog\Model\CollectionPlugin" />
    </type>
</config>

Create Plugin File
MageAcademy\Catalog\Plugin\Catalog\Model\CollectionPlugin

<?php


namespace MageAcademy\Catalog\Plugin\Catalog\Model;

use Magento\CatalogInventory\Helper\Stock;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;

class CollectionPlugin
{
    protected $stockHelper;

    public function __construct(Stock $stockHelper)
    {
        $this->stockHelper = $stockHelper;
    }

    public function aroundAddFieldToFilter(ProductCollection $subject, \Closure $proceed, $fields, $condition = null)
    {

        $this->stockHelper->addInStockFilterToCollection($subject);

        return $fields? $proceed($fields, $condition) : $subject;
    }

}
Hope this solution will work for you as well.
Leave a Reply
Your email address will not be published. *