Skip to main content

How to Create Your First CUSTOM GraphQL Query in Magento 2

Magento Headless

Over the years of evolution of e-commerce businesses, many companies turned to headless commerce due to the advantages it offers. Headless commerce clearly separates the front end from the back end of the website. This facilitates both the front end and back end to work independently. The link between these two layers are the APIs. Apart from the existing REST and SOAP APIs, Magento has introduced a new way of working with its data. This is where GraphQL comes to the scene. GraphQL is a data query language that was released by Facebook in 2015. Magento uses this to provide an alternative to the existing REST and SOAP APIs. So many developers are eager to work with this query language in order to expose the functionalities the Magento back end offers. At this point, they seek a starting point to work with GraphQL endpoints in Magento. In this article, I am focusing on creating a basic GraphQL module that will be able to fetch data from the Magento store.

 

Create Your First Query

Here we are going to create a new GraphQL query that allows us to retrieve the latest product review data for a given product id. We will use “Example” as the namespace and “ReviewGraphQL” as the module name.

First, we need to create our module.xml and registration.php files in order to introduce our new GraphQL module to the Magento codebase.

File: Example\ReviewGraphQl\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="Example_ReviewGraphQl">

        <sequence>

            <module name="Magento_Review"/>

            <module name="Magento_GraphQl"/>

        </sequence>

    </module>

</config>

File: Example\ReviewGraphQl\registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(

    \Magento\Framework\Component\ComponentRegistrar::MODULE,

    'Example_ReviewGraphQl',

    __DIR__

);

Second, we need to create a new GraphQL schema file to define our query and its parameters.

File: Example/ReviewGraphQl/etc/schema.graphqls

type Query {

    last_product_review(

    id: Int! @doc(description: "Specify the id of the product.")

    ): reviewData @resolver( class: "Example\\ReviewGraphQl\\Model\\Resolver\\Reviews") @doc(description: "Get list of reviews for the given product id.")

}

type reviewData {

    review_id: String

    created_at: String

    title: String

    detail: String

    nickname:String

}

Our custom query name is “last_product_review,” and it accepts the product id as a required parameter. The product id should be provided as an integer value. Then this custom query will invoke the functionality defined in Example\ReviewGraphQL\Model\Resolver\Reviews resolver class. Next the resolver class will grab the given product id and will get the latest review information from the database and finally will return it as the query response. We have defined the GraphQL response details above under the type “reviewData.”

Below is the code for our resolver function. 

File: Example\ReviewGraphQL\Model\Resolver\Reviews.php

<?php

declare(strict_types=1);

namespace Example\ReviewGraphQl\Model\Resolver;


use Magento\Framework\GraphQl\Config\Element\Field;

use Magento\Framework\GraphQl\Query\ResolverInterface;

use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

use Magento\Review\Model\ResourceModel\Review\CollectionFactory as ReviewCollectionFactory;

use Magento\Review\Model\Review;

use Magento\Store\Model\StoreManagerInterface;


class Reviews implements ResolverInterface

{

    protected $storeManager;

    protected $reviewCollection;


    public function __construct(

        StoreManagerInterface $storeManager,

        ReviewCollectionFactory $reviewCollection

    ) {

        $this->storeManager = $storeManager;

        $this->reviewCollection = $reviewCollection;

    }


    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)

    {

        $currentStoreId = $this->storeManager->getStore()->getId();


        $collection = $this->reviewCollection->create()

            ->addStoreFilter($currentStoreId)

            ->addStatusFilter(Review::STATUS_APPROVED)

            ->addEntityFilter('product', $args['id'])

            ->setDateOrder()

            ->getFirstItem();


        return $collection->getData();

    }

}

This query does not require you to provide any customer token. Therefore, you can execute it as below. (Note: I have used 2030 as a sample product id.) The response is shown in the right hand side.

As shown in the above image, you can get the list of reviews for any given product id. This allows you to retrieve review data for your headless Magento 2 implementations. 

This is a simple implementation of the Magento 2 GraphQL feature. I hope this will be an entry point for you to work and understand about how GraphQL queries actually work.