Get Product collection Using GraphQL Magento 2.

From the Magento version 2.3, one of the hot features for the storefront API called GraphQL is introduced.

Out of the Box Magento Products Query with all the possible fields by clicking on the link, Use Product Query GraphQl in Magento to display all the products related fields.

This example is just for learning purposes. 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 Product collection.

You can add a custom condition for getting specific Products in the Resolver PHP file based on your requirement. We will display all the products in the response.

I hope you are aware of What is GraphQL and how GraphQL is used for the programming language like Magento 2 If You are new to the 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 the 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 the dependency on the 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 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 the schema.graphql file at above.

In this Model, the 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 the query by adding the extra parameter in the 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 products in which ID is equal or greater than 1.

Now Run the 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,