Magento – Magento 2 : How to create custom GraphQl to Access Customer Data

graphqlmagento2.3magento2.3.2magento2.3.3

How to create custom GraphQl to Access Customer Data?

Best Answer

There is already an in-built GraphQl query to retrieve customer data. You can get core Magento customer data via below query.

 {
  customer {
    firstname
    lastname
    suffix
    email
    id
    addresses {
      firstname
      lastname
      street
      city
      region {
        region_code
        region
        region_id
      }
      postcode
      country_id
      telephone
    }
  }
}

The above GraphQl request will return a response shown as below.

{
  "data": {
    "customer": {
      "firstname": "John",
      "lastname": "Doe",
      "suffix": null,
      "email": "jdoe@example.com",
      "id": 3,
      "addresses": [
       {
         "firstname": "John",
         "lastname": "Doe",
         "street": [
           "123 Elm Street"
         ],
         "city": "Anytown",
         "region": {
           "region_code": "MI",
           "region": "Michigan",
           "region_id": 33
         }
         "postcode": "78758",
         "country_id": "US",
         "telephone": "512 555-1212"
        }
      ]
    }
  }
}

Refer the developer documents for more information. https://devdocs.magento.com/guides/v2.3/graphql/queries/customer.html


If you want to return your custom customer attributes via GraphQl, instead of writing a new query, you can enhance the existing customer GraphQl query.

  1. Assume you want to append a new customer attribute 'occupation' to the existing customer query. First you need to add this information in your schema.graphqls file.

app/code/YourNamespace/YourModuleGraphQl/etc/schema.graphqls

type Customer {
    occupation: String @resolver(class: "YourNamespace\\YourModuleGraphQl\\Model\\Resolver\\Customer\\Occupation")
}

'String' is the output data type when you request occupation parameter in customer query.

  1. Now create your resolver class to prepare the data for this custom attribute.

app/code/YourNamespace/YourModuleGraphQl/Model/Resolver/Customer/Occupation.php

 <?php

    declare(strict_types=1);

    namespace YourNamespace\YourModuleGraphQl\Model\Resolver\Customer;

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

    class Occupation implements ResolverInterface
    {

        protected $storeManager;

        // You can inject relevant classes in this constructor function.
        public function __construct(
            \Magento\Store\Model\StoreManagerInterface $storeManager
        )
        {
            $this->storeManager = $storeManager;
        }

        // This is the function which will get invoked when we request 'occupation' info in the graphql query 
        public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
        {
            if (!isset($value['model'])) {
                throw new LocalizedException(__('"model" value should be specified'));
            }
            $output = [];
            $customer = $value['model'];
            $customerId = (int)$customer->getId();

            // Get the custom attribute info of the customer.
            $occupation = $this->getCustomerOccupationInfo($customerId);
            $output[
                    'occupation' => $occupation;
                ];
            return $output;
        }

        private function getCustomerOccupationInfo($customerId)
        {
            // Get the value of customer's occupation attribute and return it.
            return 'Teacher';
        }
    }
  1. Run below commands.

bin/magento setup:upgrade

rm -rf generated/

bin/magento c:f

  1. Below is an example of the customer query, which implies how you can call your 'occupation' attribute inside customer query.
{
      customer {
        firstname
        lastname
        suffix
        email
        id
        occupation
        }
    }
Related Topic