In the api call V1/products i get also out of stock products, even though I've set in Stores->configuration->catalog->inventory "Display out of stock products" to No. there's a way to get rid of this annoing missing feature?
2 Answers
Magento Core team better look and fix this issue is still exist in 2.2.7 and I fixed it with a plugin in my custom module and I also added a bonus for you; this also allows you to filter products by website and store id
- Custom/ModuleName/etc/di.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:ObjectManager/etc/config.xsd"> <type name="Magento\Catalog\Model\ResourceModel\Product\Collection"> <plugin name="instockFilter" type="Custom\ModuleName\Model\Plugin\InstockFilter" /> </type> </config>
- configuration = $configuration; $this->stockHelper = $stockHelper; } public function aroundAddFieldToFilter(ProductCollection $subject, \Closure $proceed, $fields, $condition = null) { if ($this->configuration->isShowOutOfStock() != 1) { $this->stockHelper->addInStockFilterToCollection($subject); } if (is_array($fields)) { foreach ($fields as $key => $filter) { if ($filter['attribute'] == 'website_id' && isset($filter['eq'])) { $subject->addWebsiteFilter([$filter['eq']]); unset($fields[$key]); } else if ($filter['attribute'] == 'store_id' && isset($filter['eq'])) { $subject->addStoreFilter($filter['eq']); unset($fields[$key]); } } } return $fields? $proceed($fields, $condition) : $subject; } }`
You can use below procedure
create a di.xml in webrest_api folder and add below xml
<type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
<plugin name="add_stock_information" type="Magento\CatalogInventory\Model\AddStockStatusToCollection" />
</type>