Get Product collection using Graphql Magento 2.

From Magento 2.3 interact with graphQl, In GraphQl get all the product collection of Magento. Getting all the product collection using GraphQl in Magento 2 You need to create a simple module for achieving it.

We need to create a Resolver model and add our custom logic for getting all the Products collection. You can add a custom condition for getting specific Products in Resolver PHP file based on your requirement. We will display all the products in response for now.

I hope you are aware of What is GraphQl and how GraphQL are used for the programming language like Magento 2 If You are new to GraphQL check link for  GraphQl in Magento.

Now we can start the module using Magento 2 to fetch all the Products.

You need to create first registration.php and module.xml file for defining our module.

I have taken Packagename as Rbj and Module name as ProductsGraphQl.

Path: app/code/Rbj/ProductsGraphQl/registration.php

Create module.xml file, Path: app/code/Rbj/ProductsGraphQl/etc/module.xml

Our Module depends on GraphQL and Catalog Module so we have given dependency on module.xml file for each module.

Every GraphQl Module must contain schema.graphqls file under the etc folder of a module.

schema.graphqls is the heart of any GraphQL Query implementation and describes the what data can be queried. So You can define your query data basic skeleton under the schema.graphqls file.

Product Graphql Schema file,
Path: app/code/Rbj/ProductsGraphQl/etc/schema.graphqls

Now Create a Resolver Model for our custom module.  Rbj\\ProductsGraphQl\\Model\\Resolver\\ProductsResolver
ProductsResolver Model class which is defined in schema.graphql file at above.

In this Model, resolve() method will simply return data of all the Products. We only display Product SKU, name and price from products. You can add the extra field to display in the response of query by adding the extra parameter in schema.graphql file.

Path: app/code/Rbj/ProductsGraphQl/Model/Resolver/ProductsResolver.php

We have set logic for getting first all the products from ProductRepositoryInterface and apply the custom condition for getting all the product which ID is equal or greater than 1.

Now Run Upgrade command to install our module.

You can check your GraphQL query response by installing chrome extension ChromeiQL or Altair GraphQL addon via Browser.

 

Products Graphql magento 2
Products Graphql magento 2

In Request Body, You need to pass the required data(field) to request payload for getting a response of Products,

Request Payload

Result:

The result will be all Products collection which id is equal or greater than 1,

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *