Reading list Switch to dark mode

    Steps to Create GraphQL Query

    Updated 18 April 2024

    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
    
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Webkul_GraphQlCustom',
        __DIR__
    );

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

    Step 2 :- create etc/module.xml file

    Start your headless eCommerce
    now.
    Find out More
    <?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 Webkul\GraphQlCustom\Model\Resolver;
    
    use Magento\Authorization\Model\UserContextInterface;
    use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
    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;
        }
    
        /**
         * @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',
                        [\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(__($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 Magento\Framework\GraphQl\Query\ResolverInterface
    • “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.

    Selection_057
    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/

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • salah
    • Ritika Singh (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home