Steps to Create GraphQL Query
Below are the Steps that you can use to create a module as well as GraphQL query in Magento and use it in place of any REST APIs.
Create a registration file in the folder in the path below.
Step 1 :- Create a registration.php file
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Webkul_GraphQlCustom',
__DIR__
);
Create a module.xml file in the path below.
Step 2 :- Create a 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">
<sequence>
<module name="Magento_Customer"/>
<module name="Magento_Authorization"/>
<module name="Magento_GraphQl"/>
</sequence>
</module>
</config>
Create a schema.graphqls file in the path below. This file is used for adding the query schema and mutation schema, and its path.
This file contains all the things which are related to the resolver class, as well as a description of the query.
Step 3 :- GraphQL queries are declared under the 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
}
Explanation of GraphQL:-
- type Query > declares Query operations of our module.
- testcustomer > name of our query.
- email: String > input 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 the model resolver class.
You can give any name to this file according to your needs.
Setp 4 :- Create a 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;
/**
* @var CustomerRepositoryInterface
*/
private $customerRepository;
/**
* Constructor
*
* @param ValueFactory $valueFactory
* @param CustomerFactory $customerFactory
* @param ServiceOutputProcessor $serviceOutputProcessor
* @param ExtensibleDataObjectConverter $dataObjectConverter
* @param CustomerRepositoryInterface $customerRepository
* @param \Psr\Log\LoggerInterface $logger
*/
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;
}
/**
* Resolver Method
*
* @param Field $field
* @param ContextInterface $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()));
}
}
/**
* Get Customer Data
*
* @param string $customerEmail
* @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()));
}
}
}
Explanation:-
- 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, check the output by running the below query
{
testcustomer(email: "test@webkul.in") {
entity_id
firstname
lastname
email
created_in
created_at
}
}
Run the above GraphQL query in Postman by selecting GraphQL in the body and type as POST.
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/
If you need any technical support, please get in touch with us at support@webkul.com
Additionally, unlock powerful enhancements for your Magento 2 store by exploring our Magento 2 plugins.
Turn your ideas into powerful features with expert Magento 2 developers.