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
create di.xml and put below code
<?xml version="1.0"?>

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

Create Plugin File


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)


        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. *