Create a custom GraphQL Query & Mutation in Magento 2

Today we will see how to write a GraphQL queries and mutation and i am hoping that your already aware about the graphql concept but still i will give you quick introduction on that GraphQL is a query language for API to allow the customers to fetch the required data while the server returns only the required information. GraphQL was introduced in Magento 2.3 to replace REST and SOAP API. GraphQL is used to read data by query and write data to the server through a mutation.

Steps to Create Custom GraphQL Query in Magento 2:

Step 1: First, we need to create a “schema.graphqls” file inside our extension at the below path.

app\code\Learn\GraphQLExample\etc\schema.graphqls

Now, add the below code

type Query {
    getCustomerDetailsQuery (
        email: String! @doc(description: "customer email")
    ): customerDetailsQueryOutput @resolver(class: "\\Learn\\GraphQLExample\\Model\\Resolver\\CustomerDetailsQuery") @doc(description:"get the customer details")
}

type customerDetailsQueryOutput {
    customer_id: String!
    firstname: String!
    lastname: String!
    email: String!
}

Step 2: After that, we need to create a “CustomerDetailsQuery.php” file inside the below folder path of the extension.

app\code\Learn\GraphQLExample\Model\Resolver\CustomerDetailsQuery.php

Now, add the below code

<?php

namespace Learn\GraphQLExample\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\Exception\NoSuchEntityException;

class CustomerDetailsQuery implements ResolverInterface
{
    private $customerRepository;

    public function __construct(
        \Magento\Customer\API\CustomerRepositoryInterface $customerRepository
    )
    {
        $this->customerRepository = $customerRepository;
    }

    public function resolve(
        Field       $field,
                    $context,
        ResolveInfo $info,
        array       $value = null,
        array       $args = null
    )
    {
        if (!isset($args['email'])) {
            throw new GraphQlInputException(__('"email should be specified'));
        }
        try {
            $customerObj = $this->getCustomerByEmail($args['email']);
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__('Could not find a customer with EMAIL "%email"', ['email' => $args['email']]));
        }

        if ($customerObj) {
            $data['customer_id'] = $customerObj->getId();
            $data['firstname'] = $customerObj->getFirstname();
            $data['lastname'] = $customerObj->getLastname();
            $data['email'] = $customerObj->getEmail();
        } else {
            throw new GraphQlInputException(__('"customer is not exist in website'));
        }
        return $data;
    }

    public function getCustomerByEmail($email, $websiteId = null)
    {
        return $this->customerRepository->get($email, $websiteId);
    }
}

You need to test GraphQL Query in Altair GraphQL client chrome extension or you can also test in Postman Software.

The response will be as shown below,

Query Request :

query {
  getCustomerDetailsQuery(
    email: "chelumallap@gmail.com"
  ) {
    customer_id
    firstname
    lastname
    email
  }
}

Reference Image


Steps to Create Custom GraphQL Mutation in Magento 2:

Step 1: First, we need to create a “schema.graphqls” file inside our extension at the below path.

app\code\Learn\GraphQLExample\etc\schema.graphqls

Now, add the below code

type Mutation {
    getCustomerDetailsMutation(input: customerInput!): CustomerDetailsMutationOutput @resolver(class: "\\Learn\\GraphQLExample\\Model\\Resolver\\CustomerDetailsMutation") @doc(description:"get the customer details")
}

input customerInput {
    email: String @doc(description: "customer email")
}

type CustomerDetailsMutationOutput {
   customer_id: String!
       firstname: String!
       lastname: String!
       email: String!
}

Step 2: After that, we need to create a “CustomerDetailsMutation.php” file inside the below folder path of the extension.

app\code\Learn\GraphQLExample\Model\Resolver\CustomerDetailsMutation.php

Now, add the below code

<?php

namespace Learn\GraphQLExample\Model\Resolver;

use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\Exception\NoSuchEntityException;

class CustomerDetailsMutation implements ResolverInterface
{
    private $customerRepository;

    public function __construct(
        \Magento\Customer\API\CustomerRepositoryInterface $customerRepository
    )
    {
        $this->customerRepository = $customerRepository;
    }

    /**
     * @param Field $field
     * @param \Magento\Framework\GraphQl\Query\Resolver\ContextInterface $context
     * @param ResolveInfo $info
     * @param array|null $value
     * @param array|null $args
     * @return array|\Magento\Framework\GraphQl\Query\Resolver\Value|mixed
     * @throws GraphQlInputException
     */
    public function resolve(
        Field       $field,
                    $context,
        ResolveInfo $info,
        array       $value = null,
        array       $args = null
    )
    {

        if (!isset($args['input']['email'])) {
            throw new GraphQlInputException(__('"email should be specified'));
        }

        try {
            $customerObj = $this->getCustomerByEmail($args['input']['email']);
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__('Could not find a customer with EMAIL "%email"', ['email' => $args['input']['email']]));
        }

        if ($customerObj) {
            $data['customer_id'] = $customerObj->getId();
            $data['firstname'] = $customerObj->getFirstname();
            $data['lastname'] = $customerObj->getLastname();
            $data['email'] = $customerObj->getEmail();
        }

        return $data;
    }

    public function getCustomerByEmail($email, $websiteId = null)
    {
        return $this->customerRepository->get($email, $websiteId);
    }
}

You need to test GraphQL Query in Altair GraphQL client chrome extension or you can also test in Postman Software.

The response will be as shown below,

Mutation Request :

mutation getCustomerDetailsMutation($email: String!){
  getCustomerDetailsMutation(input: {email:$email}){
    customer_id
    email
    firstname
    lastname
  }
}

Reference Image

If you have any questions or feedback so please feel free to ask in the comments or reach me my email address chelumallap@gmail.com

Thank you so much for reading this blog and keep support me and i will coming with the new blog.

Related Posts

Leave a Reply

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