Magento 2 REST API:如何在搜索条件中过滤缺货商品?
Great question! Let's tackle this—you want to exclude configurable products where all their variants are out of stock from your API results. Here's how to adjust your search criteria to make that happen:
Modified API Call
First, here's the updated API request that adds inventory-based filtering:
{{base_url}}/rest/V1/products?searchCriteria[filter_groups][0][filters][0][condition_type]=like&searchCriteria[filter_groups][0][filters][0][field]=description&searchCriteria[filter_groups][0][filters][0][value]=%t shirt%&searchCriteria[filter_groups][1][filters][0][field]=type_id&searchCriteria[filter_groups][1][filters][0][value]=configurable&searchCriteria[filter_groups][2][filters][0][field]=stock_item.is_in_stock&searchCriteria[filter_groups][2][filters][0][condition_type]=eq&searchCriteria[filter_groups][2][filters][0][value]=1
How This Works
Magento automatically aggregates inventory status for configurable products based on their linked simple variants:
- If any variant is in stock, the configurable product's
stock_item.is_in_stockfield will be set to1 - Only when all variants are out of stock will this field be
0
By adding the third filter group checking stock_item.is_in_stock=1, you're telling the API to only return configurable products that have at least one in-stock variant—exactly what you need.
For Strict Inventory Checks (Optional)
If you want to go a step further and ensure at least one variant has a positive stock quantity (not just marked as in-stock), add an extra filter group for quantity:
{{base_url}}/rest/V1/products?searchCriteria[filter_groups][0][filters][0][condition_type]=like&searchCriteria[filter_groups][0][filters][0][field]=description&searchCriteria[filter_groups][0][filters][0][value]=%t shirt%&searchCriteria[filter_groups][1][filters][0][field]=type_id&searchCriteria[filter_groups][1][filters][0][value]=configurable&searchCriteria[filter_groups][2][filters][0][field]=stock_item.is_in_stock&searchCriteria[filter_groups][2][filters][0][condition_type]=eq&searchCriteria[filter_groups][2][filters][0][value]=1&searchCriteria[filter_groups][3][filters][0][field]=stock_item.qty&searchCriteria[filter_groups][3][filters][0][condition_type]=gt&searchCriteria[filter_groups][3][filters][0][value]=0
This adds a check that the product's aggregated stock quantity is greater than 0, ensuring there's actual inventory available for at least one variant.
Key Notes
- Make sure your Magento instance has inventory aggregation for configurable products enabled (this is the default setting)
- If you're using Magento's Multi-Source Inventory (MSI), you may need to adjust the field to
extension_attributes.stock_item.is_in_stockdepending on your version and configuration
内容的提问来源于stack exchange,提问作者Arun SS

