From Magento version 2.3, one of the latest 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 collections 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 requirements. We will display all the products in the response.
I hope you are aware of What is GraphQL and how GraphQL is used for programming languages 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 the first registration.php and module.xml files to define our module.
I have taken Packagename as Rbj and Module name as ProductsGraphQl.
Path: app/code/Rbj/ProductsGraphQl/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Rbj_ProductsGraphQl', __DIR__ );
Create module.xml file, Path: app/code/Rbj/ProductsGraphQl/etc/module.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="Rbj_ProductsGraphQl"> <sequence> <module name="Magento_Catalog"/> <module name="Magento_GraphQl"/> </sequence> </module> </config>
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 a 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
type Query { productCollection: ProductCollection @resolver(class: "Rbj\\ProductsGraphQl\\Model\\Resolver\\ProductsResolver") @doc(description: "Get Product collection of a store") } type ProductCollection @doc(description: "product collection comment") { allProducts: [ProductRecord] @doc(description: "Product records with info") } type ProductRecord { sku: String @doc(description: "Get Product sku") name: String @doc(description: "Get Product name") price: Float @doc(description: "Get Product price") }
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
<?php declare(strict_types=1); namespace Rbj\ProductsGraphQl\Model\Resolver; use Magento\Catalog\Api\ProductRepositoryInterface; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\GraphQl\Config\Element\Field; use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException; use Magento\Framework\GraphQl\Query\ResolverInterface; use Magento\Framework\GraphQl\Schema\Type\ResolveInfo; /** * Product collection resolver */ class ProductsResolver implements ResolverInterface { public function __construct( private readonly ProductRepositoryInterface $productRepository, private readonly SearchCriteriaBuilder $searchCriteriaBuilder ) { } /** * @inheritdoc */ public function resolve( Field $field, $context, ResolveInfo $info, array $value = null, array $args = null ) { $productsData = $this->getProductsData(); return $productsData; } /** * @return array * @throws GraphQlNoSuchEntityException */ private function getProductsData(): array { try { /* filter for all the pages */ $searchCriteria = $this->searchCriteriaBuilder->addFilter('entity_id', 1,'gteq')->create(); $products = $this->productRepository->getList($searchCriteria)->getItems(); $productRecord['allProducts'] = []; foreach($products as $product) { $productId = $product->getId(); $productRecord['allProducts'][$productId]['sku'] = $product->getSku(); $productRecord['allProducts'][$productId]['name'] = $product->getName(); $productRecord['allProducts'][$productId]['price'] = $product->getPrice(); } } catch (NoSuchEntityException $e) { throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e); } return $productRecord; } }
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.
php bin/magento setup:upgrade php bin/magento cache:flush
You can check your GraphQL query response by installing the Chrome extension ChromeiQL or Altair GraphQL addon via Browser.
In Request Body, You need to pass the required data(field) to request payload for getting a response of Products,
Request Payload
{ productCollection { allProducts { sku name price } } }
Result:
The result will be all product collections whose id is equal to or greater than 1,
{ "data": { "productCollection": { "allProducts": [ { "sku": "Test Product 1", "name": "Test Product 1", "price": 100 }, { "sku": "Test Product 2", "name": "Test Product 2", "price": 199.5 }, { "sku": "Configurable Product Demo", "name": "Configurable Product Demo", "price": 0 } ] } } }