How to filter by category in Magento 2's API?
Asked Answered
S

2

5

In Magento 2's REST API, there is an option to search a product using various search criteria. As you know, an example is given below:

http://magentohost/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=name& searchCriteria[filter_groups][0][filters][0][value]=%macbook%& searchCriteria[filter_groups][0][filters][0][condition_type]=like

But I have not found an option to search by category.

How can we do that?

Scrannel answered 9/2, 2017 at 20:37 Comment(0)
M
9

To search by category, it is simple. You have to just pass category_id as a field. Have a look at below example:

http://magentohost/rest/V1/products?searchCriteria[filterGroups][0][filters][0][field]=category_id& searchCriteria[filterGroups][0][filters][0][value]=4& searchCriteria[filterGroups][0][filters][0][conditionType]=eq&searchCriteria[sortOrders][0][field]=created_at& searchCriteria[sortOrders][0][direction]=DESC& searchCriteria[pageSize]=10& searchCriteria[currentPage]=1
Malcolmmalcom answered 2/4, 2017 at 8:10 Comment(0)
F
0

You can also target multiple categories at once:

searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=1,2,3&searchCriteria[filter_groups][0][filters][0][condition_type]=in&searchCriteria[sort_orders][0][field]=created_at&searchCriteria[sort_orders][0][direction]=DESC&searchCriteria[current_page]=1&searchCriteria[page_size]=10

I have a little lib - https://github.com/dsheiko/magentosearchquerybuilder, which helps me building such queries

$builder = new SearchCriteria();
$builder
    ->filterGroup([
        [ "category_id", implode(",", $categories), SearchCriteria::OP_IN ],
    ])
    ->sortOrder( "created_at", "DESC")
    ->limit(1, 10);


echo $builder->toString();
Fete answered 14/12, 2017 at 9:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.