Is there a way to fetch custom filters for a particular category in Magento 2 using Rest api?

Viewed 1129

I am using the url below to fetch the products in a particular category and it works fine.

/rest/default/V1/products?searchCriteria[filterGroups][0][filters][0][field]=category_id&searchCriteria[filterGroups][0][filters][0][value]=262&searchCriteria[filterGroups][0][filters][0][conditionType]=eq&searchCriteria[filterGroups][1][filters][0][field]=visibility&searchCriteria[filterGroups][1][filters][0][value]=4&searchCriteria[filterGroups][1][filters][0][conditionType]=eq&searchCriteria[pageSize]=10&searchCriteria[currentPage]=0

The only issue is that I would like to show filters based on the categories selected. For eg a price filter works for every category but a size and color filter would only work for clothing category while screen size would work for electronics.

Any idea on how to fetch the filters for each category?

2 Answers

You can try magento search api to get filters by passing category or any other field like below example.

{{url}}/rest/V1/search?searchCriteria[requestName]=catalog_view_container&searchCriteria[filterGroups][0][filters][0][field]=category_ids&searchCriteria[filterGroups][0][filters][0][value]=10

Result will have category and other buckets, something like below:

[
  {
    "name": "category_bucket",
    "values": [
      {
        "value": "2",
        "metrics": [
          2,
          634
        ]
      },
      {
        "value": "10",
        "metrics": [
          10,
          634
        ]
      }
    ]
  },
  {
    "name": "brand_bucket",
    "values": [
      {
        "value": "617",
        "metrics": [
          617,
          562
        ]
      },
      {
        "value": "639",
        "metrics": [
          639,
          29
        ]
      },
      {
        "value": "1218",
        "metrics": [
          1218,
          26
        ]
      },
      {
        "value": "640",
        "metrics": [
          640,
          8
        ]
      },
      {
        "value": "1332",
        "metrics": [
          1332,
          4
        ]
      }
    ]
  }
]

You can map this result with attribute api result to get label {{url}}/rest/all/V1/products/attributes?searchCriteria=&fields=items[attribute_id,attribute_code,options,frontend_labels]

I found the answer ,but I had to switch from using rest api to graphql as graphql supports aggregations . This was exactly what I needed and also seems like graphql has more features as compared to rest api for magento 2.

Related