GraphQL

GraphQL is a query language for APIs.GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.GraphQL isn’t tied to any specific database or storage engine and is instead backed by your existing code and data.

GraphQL in Magento

With the rise of the PWA in Magento, there is a need to get smaller amounts of data and to make fewer API requests. GraphQL’s query language makes this possible by allowing the requestor to request a limited subset of attributes to be returned about an entity (significantly smaller responses) and allows you to chain requests (smaller number of requests). Magento uses GraphQL to provide an alternative to REST and SOAP web APIs for frontend development.

Magento 2.3 natively supports GraphQL, while running the project we will get an interface to work with GraphQL. The following image shows a sample query and results to get product information by its SKU using default GraphQL schema.

In this example, the left part showing the query and the right part is the result. The query fetches the product SKU, name, price, regular price, description etc. of a product with SKU  “VP01-RN-XS”.

Case study: Custom module to get customer information using GraphQL.
In this custom module, we create custom GraphQl schema to get customer information using their email id.

Note: You need to install Magento 2.3 with PWA – Venia theme to try below example.

Step 1: Register new module

First of all, we need to register the custom module (Titech_TestGraphQl) from below path.

File path: <path to your magento>/app/code/Titech/TestGraphQl/registration.php

 <?php

/**

 * @package   Titech_TestGraphQl

 * @author    Titech

 */

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

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

    ‘Titech_TestGraphQl’,

    __DIR__

);

?>

Step 2: Create a module.xml file

Then, we need to create a module.xml file for declaring components.

File path: <path to your magento>/app/code/Titech/TestGraphQl/etc/module.xml

<?xml version=”1.0″?>

<!–

/**

 * @package   Titech_TestGraphQl

 * @author    Titech

 */

–>

<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”urn:magento:framework:Module/etc/module.xsd”>

    <module name=”Titech_TestGraphQl” >

        <sequence>

            <module name=”Magento_Customer”/>

            <module name=”Magento_Authorization”/>

            <module name=”Magento_GraphQl”/>

        </sequence>

    </module>

</config>

Step 3: Define schema
We have to define the schema of query. In this schema, we need to mention the fields and type of data in the response.

File path: <path to your magento>/app/code/Titech/TestGraphQl/etc/schema.graphqls

#Magento Customer GraphQl Schema

type Query {

            testcustomer(

        email: String @doc(description: “Id of the customer”)

    ): Testcustomer @resolver(class: “Titech\\TestGraphQl\\Model\\Resolver\\Customer”) @doc(description:

    “The testcustomer query returns information about a customer”)

}

type Testcustomer @doc(description: “Testcustomer defines the customer name and other details”) {

    entity_id: Int

    firstname: String

    lastname: String

    email: String

}

Step 4:  Create resolver model class for schema

We need to create a resolver model class against the schema definition. Through this method, we simply return data of customer with the requested email id.

<path to your magento> /app/code/Titech/TestGraphQl/Model/Resolver/Customer.php

<?php

declare(strict_types=1);

namespace Titech\TestGraphQl\Model\Resolver;

use Magento\Authorization\Model\UserContextInterface;

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

use Titech\TestGraphQl\Model\Resolver\Customer\CustomerDataProvider;

use Magento\Framework\Exception\NoSuchEntityException;

use Magento\Framework\Exception\LocalizedException;

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

use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;

use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;

use Magento\Framework\GraphQl\Query\Resolver\ContextInterface;

use Magento\Framework\GraphQl\Query\Resolver\Value;

use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;

use Magento\Framework\GraphQl\Query\ResolverInterface;

use Magento\Customer\Model\CustomerFactory;

use Magento\Customer\Api\CustomerRepositoryInterface;

use Magento\Customer\Api\Data\CustomerInterface;

use Magento\Framework\Webapi\ServiceOutputProcessor;

use Magento\Framework\Api\ExtensibleDataObjectConverter;

/**

 * Customers field resolver, used for GraphQL request processing.

 */

class Customer implements ResolverInterface

{

    /**

    * @var ValueFactory

    */

    private $valueFactory;

    /**

    * @var CustomerFactory

    */

    private $customerFactory;

    /**

    * @var ServiceOutputProcessor

    */

    private $serviceOutputProcessor;

    /**

    * @var ExtensibleDataObjectConverter

    */

    private $dataObjectConverter;

    /**

    * @var \Psr\Log\LoggerInterface

    */

    private $logger;

    /**

     *

     * @param ValueFactory $valueFactory

     * @param CustomerFactory $customerFactory

     * @param ServiceOutputProcessor $serviceOutputProcessor

     * @param ExtensibleDataObjectConverter $dataObjectConverter

     */

    public function __construct(

        ValueFactory $valueFactory,

        CustomerFactory $customerFactory,

        ServiceOutputProcessor $serviceOutputProcessor,

        ExtensibleDataObjectConverter $dataObjectConverter,

        CustomerRepositoryInterface $customerRepository,

        \Psr\Log\LoggerInterface $logger

    ) {

        $this->valueFactory = $valueFactory;

        $this->customerFactory = $customerFactory;

        $this->serviceOutputProcessor = $serviceOutputProcessor;

        $this->dataObjectConverter = $dataObjectConverter;

        $this->customerRepository = $customerRepository;

        $this->logger = $logger;

    }

    /**

    * {@inheritdoc}

    */

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

        if (!isset($args[’email’])) {

            throw new GraphQlAuthorizationException(

                __(

                    ’email for customer should be specified’,

                    [\Magento\Customer\Model\Customer::ENTITY]

                )

            );

        }

        try {

            $data = $this->getCustomerData($args[’email’]);

            $result = function () use ($data) {

                return !empty($data) ? $data : [];

            };

            return $this->valueFactory->create($result);

        } catch (NoSuchEntityException $exception) {

            throw new GraphQlNoSuchEntityException(__($exception->getMessage()));

        } catch (LocalizedException $exception) {

            throw new GraphQlNoSuchEntityException(__($e->getMessage()));

        }

    }

    /**

    *

    * @param int $context

    * @return array

    * @throws NoSuchEntityException|LocalizedException

    */

    private function getCustomerData($customerId) : array

    {

        try {

            $customerData = [];

            $customerColl = $this->customerFactory->create()->getCollection()

                                                    ->addFieldToFilter(“email”, [“eq”=>$customerId]);

            foreach ($customerColl as $customer) {

                array_push($customerData, $customer->getData());

            }

            return isset($customerData[0])?$customerData[0]:[];

        } catch (NoSuchEntityException $e) {

           return [];

        } catch (LocalizedException $e) {

            throw new NoSuchEntityException(__($e->getMessage()));

        }

    }

}

Step 5: Install module
Go to the project folder via terminal and run the following command to install this module.

1 – php bin/magento setup:upgrade
2 – php bin/magento cache:flush

Step 6: Check the response
You can check your GraphQL query and response by installing a chrome extension “ChromeiQL”. Then, set the endpoint as “<your magento root url>/graphql”.

After that, input your GraphQL query in the left side of “ChromeiQL” interface and click on the “Run” button. Now, you will get the result on the right side!

 

If you are searching for the best Magento developer for your websites, you can send us an email on [email protected] or drop a line in our contact us page.

 

Shaarif is one of the senior magento developer working with ti Technologies. Shaarif is experienced in working with Magento2 development and he is expert in magento2 development, module development, upgrading magento 1.x to latest Magento2 version.