Steps to Create graphql query

Below are the Steps that you can Create a module as well as GraphQl Query in Magento and use it in place of any rest apis.

Create a registration file in folder in the below path.

Step 1 :- You Create registration.php file

<?php

MagentoFrameworkComponentComponentRegistrar::register(
    MagentoFrameworkComponentComponentRegistrar::MODULE,
    'Webkul_GraphQlCustom',
    __DIR__
);

Create module.xml file in the below path in a folder

Step 2 :- create etc/module.xml file

<?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="Webkul_GraphQlCustom" setup_version="1.0.0">        
        <sequence>
                <module name="Magento_Customer"/>
                <module name="Magento_Authorization"/>
                <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>

Create Schema.graphqls file in the below path in a folder. this file is used for adding the query schema and muatation schema and its path. this file contains all the things which are related to resolver class as well as description in query.

Step 3 :- GraphQL queries are declared under folder etc/schema.graphqls

type Query {
    testcustomer( email: String @doc(description: "email of the customer")): Testcustomer @resolver(class:"Webkul\GraphQlCustom\Model\Resolver\Customer") @doc(description:"The test customer 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
    created_in: String
    created_at: String
}

Explaintion of graphqls :-

  • type Query > declares Query operations of our module.
  • testcustomer > name of our query.
  • email: String > nput name (email) and type (string).
  • Test customer > defines the identity of the query, including resolver (@resolver) class, document (@doc), is the result cacheable (@cache), etc.
  • type Test customer > define the result object of the query, including their name and type.

Below is the file for model resolver class.

You can give any name to this file according to your need.

Setp 4 :- Create Resolver Class Model/Resolver/Customer.php

<?php

namespace WebkulGraphQlCustomModelResolver;

use MagentoAuthorizationModelUserContextInterface;
use MagentoFrameworkGraphQlSchemaTypeResolveInfo;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkGraphQlConfigElementField;
use MagentoFrameworkGraphQlExceptionGraphQlAuthorizationException;
use MagentoFrameworkGraphQlExceptionGraphQlNoSuchEntityException;
use MagentoFrameworkGraphQlQueryResolverContextInterface;
use MagentoFrameworkGraphQlQueryResolverValue;
use MagentoFrameworkGraphQlQueryResolverValueFactory;
use MagentoFrameworkGraphQlQueryResolverInterface;
use MagentoCustomerModelCustomerFactory;
use MagentoCustomerApiCustomerRepositoryInterface;
use MagentoCustomerApiDataCustomerInterface;
use MagentoFrameworkWebapiServiceOutputProcessor;
use MagentoFrameworkApiExtensibleDataObjectConverter;

/**
 * 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 PsrLogLoggerInterface
     */
    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,
        PsrLogLoggerInterface $logger
    ) {
        $this->valueFactory = $valueFactory;
        $this->customerFactory = $customerFactory;
        $this->serviceOutputProcessor = $serviceOutputProcessor;
        $this->dataObjectConverter = $dataObjectConverter;
        $this->customerRepository = $customerRepository;
        $this->logger = $logger;
    }

    /**
     * @param Field $field
     * @param [type] $context
     * @param ResolveInfo $info
     * @param array|null $value
     * @param array|null $args
     * @return array
     */
    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',
                    [MagentoCustomerModelCustomer::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(__($exception->getMessage()));
        }
    }

    /**
     *
     * @param int $context
     * @return array
     * @throws NoSuchEntityException|LocalizedException
     */
    private function getCustomerData($customerEmail) : array
    {
        try {
            $customerData = [];
            $customerColl = $this->customerFactory->create()->getCollection()->addFieldToFilter('email', ['eq'=>$customerEmail]);
            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()));
        }
    }
}

Explaintion :-

  • Resolver class must implement MagentoFrameworkGraphQlQueryResolverInterface
  • “resolve” is the main method of this class, with $args as the query’s input

Setp 5 :- Final step you check output. Run this query

{
    testcustomer(email: "[email protected]") {
        entity_id
        firstname
        lastname
        email
        created_in
        created_at
    }
}

Run Above GraphQl Query in Postman by selecting GraphQl in body and type as post.

Postman view

Learn more from this link : https://developer.adobe.com/commerce/webapi/graphql/

check for other blogs as well: https://webkul.com/blog/graphql-mutation-2/


Source link