In today's tutorial, we will explain on how to get products by category using GraphQL in Magento 2. After the launch of Magento 2.3.x, we can use GraphQL that can be considered as an alternate option of REST API and SOAP API.
GraphQL is a query language for the API which is used to load only requested data from server. With REST API it is easy to fetch products by category. But with GraphQL, here is a step by step tutorial to do it.
Follow the below steps:
Execute URL : {baseURL}/graphql
Where Base URL: http://125.0.0.1/m235/ (your store base url) and End Point : graphql
In Request Body, You need to pass the below data.
Request:
{ products( filter: {category_id: {eq: "3"}}, sort: {name: ASC}, pageSize: 2, currentPage: 1 ) { total_count items { name sku price_range { minimum_price { regular_price { value currency } final_price { value currency } discount { amount_off percent_off } } maximum_price { regular_price { value currency } final_price { value currency } discount { amount_off percent_off } } } } } }
Here, you need to pass category id in graphql query request.
Output:
{ "data": { "products": { "total_count": 35, "items": [ { "name": "Affirm Water Bottle ", "sku": "24-UG06", "price_range": { "minimum_price": { "regular_price": { "value": 7, "currency": "USD" }, "final_price": { "value": 7, "currency": "USD" }, "discount": { "amount_off": 0, "percent_off": 0 } }, "maximum_price": { "regular_price": { "value": 7, "currency": "USD" }, "final_price": { "value": 7, "currency": "USD" }, "discount": { "amount_off": 0, "percent_off": 0 } } } }, { "name": "Aim Analog Watch", "sku": "24-MG04", "price_range": { "minimum_price": { "regular_price": { "value": 45, "currency": "USD" }, "final_price": { "value": 45, "currency": "USD" }, "discount": { "amount_off": 0, "percent_off": 0 } }, "maximum_price": { "regular_price": { "value": 45, "currency": "USD" }, "final_price": { "value": 45, "currency": "USD" }, "discount": { "amount_off": 0, "percent_off": 0 } } } } ] } } }
That's it!
We hope we have helped you through the process of getting products by category using GraphQL in Magento 2. If we missed out anything, feel free to reach out!
Also read: How To Get A Product By GraphQL In Magento 2?