Read More
Read More
Menu Close

    GraphQl implementation in Magento2

    What is GraphQl –  GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API.Using GraphQL we create own schema which is organized in terms of types and fields.GraphQL uses types to ensure channel only ask for what’s possible and provide clear and helpful errors.

    This blog assumes your familiarity with GraphQL concepts. If it is not the case – first learn about GraphQL on the official website or you can read our previous blog How to use GraphQL in php.

    Note :- GraphQL included in Magento 2.3.0 

    For implementing GraphQL in magento2 you have to create following files :-

    1 – create this file for register your module app/code/Test/TestGraphQl/registration.php

    Searching for an experienced
    Magento 2 Company ?
    Read More
    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Test_TestGraphQl
     * @author    Webkul
     * @license   https://store.webkul.com/license.html
     */
    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Test_TestGraphQl',
        __DIR__
    );
    

    2 – For define module name you have to create app/code/Test/TestGraphQl/etc/module.xml

    <?xml version="1.0"?>
    <!--
    /**
    * Webkul Software.
    *
    * @category  Webkul
    * @package   Test_TestGraphQl
    * @author    Webkul
    * @license   https://store.webkul.com/license.html
    */
    -->
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Test_TestGraphQl" >
            <sequence>
                <module name="Magento_Customer"/>
                <module name="Magento_Authorization"/>
                <module name="Magento_GraphQl"/>
            </sequence>
        </module>
    </config>
    

    3 – First we have to define Schema of  query.In this part we mention that which fields and which type of data return in response.The schema is a container of your type hierarchy, which accepts root types in a constructor and provides methods for receiving information about your types to internal GrahpQL tools.The schema consists of two root types:

    • Query type is a surface of your read API
    • Mutation type (optional) exposes write API by declaring all possible mutations in your app

    In this blog we learn about only Query type.

    create schema.graphqls at this path app/code/Test/TestGraphQl/etc/

    #Magento Customer GraphQl Schema
    
    type Query {
        testcustomer: Testcustomer @resolver(class: "Test\\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
    }
    

    4 – Create Resolver Model class which is define in schema.In this resolve method we simply return data of login customer.

    <?php
    
    declare(strict_types=1);
    
    namespace Test\TestGraphQl\Model\Resolver;
    
    use Magento\Authorization\Model\UserContextInterface;
    use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
    use Test\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
        ) : Value {
            if ((!$context->getUserId()) || $context->getUserType() == UserContextInterface::USER_TYPE_GUEST) {
                throw new GraphQlAuthorizationException(
                    __(
                        'Current customer does not have access to the resource "%1"',
                        [\Magento\Customer\Model\Customer::ENTITY]
                    )
                );
            }
    
            try {
                $data = $this->getCustomerData($context->getUserId());
                $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("entity_id", ["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()));
            }
        }
    }
    

    Please run following command to install this module.

    1 – php bin/magento setup:upgrade

    2 – php bin/magento cache:flush

    You can check your GraphQL query response by installing chrome extension ChromeiQL.

    Graphql implementation

    For checking your query first you have to set endpoint.

    <magento root url>/graphql

    Magento use GraphQL module to manage all predefined or custom GraphQL queries.

    After set your endpoint you can see your custom query under section of document explorer.

    Mean while Please try the above example and If you have any Query then please feel free to put it in comment section.

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    4 comments

  • rupesh jadhav
    Cool. Nice Document
    • Subhangi (Moderator)

      Hello Rupesh,

      Thanks for the appreciation.

       

  • vishal
    where to define schema in document doesn’t mention
    • Shubham Sharma (Moderator)
      Hello Vishal,
      Crete schema.graphqls at this path app/code/Test/TestGraphQl/etc/
  • Back to Top