Back to Top

How to Implement GraphQL in Magento 2

Updated 30 December 2025

Modern eCommerce applications demand fast, flexible, and efficient data retrieval—especially for headless storefronts, mobile apps, and PWAs. This is where GraphQL comes into play.

What Is GraphQL? (Simple & Clear Explanation)

GraphQL is a modern query language for APIs created by Facebook.


Unlike REST APIs—where you often fetch too much or too little data—GraphQL allows clients to request exactly what they need, and nothing more.

Key Advantages of GraphQL

  • Single endpoint (no more multiple REST URLs)
  • Client controls the response (fetch only required fields)
  • Fewer network calls (batching of queries)
  • Strongly typed schema (makes APIs predictable)
  • Perfect for headless Magento, PWAs, and mobile apps

Magento 2 adopted GraphQL to support Luma, PWA Studio, and modern headless architectures.

Searching for an experienced
Magento 2 Company ?
Find out More


But often, you need to build custom GraphQL endpoints for business logic—and that’s exactly what we’ll do in this blog.

GraphQL uses types to ensure channel only ask for what’s possible and provide clear and helpful errors. Also, you can check how to create REST API in Magento 2.

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.

What We Will Build

We will create a Magento 2 GraphQL module that provides a custom query:

customerDetails

This query will return the logged-in customer’s:

  • ID
  • Firstname
  • Lastname
  • Email

And we will secure it so that only authenticated customers can access it.

1. Module Folder Structure

app/code/Webkul/CustomerGraphQl/
│
├── etc
│   └── module.xml
│
├── etc/schema.graphqls
│
├── registration.php
│
└── Model/Resolver/CustomerDetails.php

2. module.xml

<?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_CustomerGraphQl"/>
</config>

3. registration.php

<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Webkul_CustomerGraphQl',
    __DIR__
);

4. schema.graphqls

This defines the GraphQL type and query.

app/code/Webkul/CustomerGraphQl/etc/schema.graphqls

type CustomerDetailsOutput {
    id: Int
    firstname: String
    lastname: String
    email: String
}

type Query {
    customerDetails: CustomerDetailsOutput 
        @resolver(class: "Webkul\\CustomerGraphQl\\Model\\Resolver\\CustomerDetails")
}

5. Resolver to Return Logged-In Customer Data

app/code/Webkul/CustomerGraphQl/Model/Resolver/CustomerDetails.php

<?php

namespace Webkul\CustomerGraphQl\Model\Resolver;

use Magento\CustomerGraphQl\Model\Customer\GetCustomer;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Framework\GraphQl\Exception\GraphQlAuthorizationException;

class CustomerDetails implements ResolverInterface
{
    /**
     * @var GetCustomer
     */
    private $getCustomer;

    public function __construct(
        GetCustomer $getCustomer
    ) {
        $this->getCustomer = $getCustomer;
    }

    /**
     * Resolver method for GraphQL
     *
     * @param Field $field
     * @param \Magento\GraphQl\Model\Query\ContextInterface $context
     * @param ResolveInfo $info
     * @param array $value
     * @param array $args
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        if ($context->getExtensionAttributes()->getIsCustomer() === false)    {
                throw new GraphQlAuthorizationException(
                    __('The current customer isn\'t authorized.')
                );
        }
        $customer = $this->getCustomer->execute($context);

        return [
            'id'        => $customer->getId(),
            'firstname' => $customer->getFirstname(),
            'lastname'  => $customer->getLastname(),
            'email'     => $customer->getEmail()
        ];
    }
}

6. Run Magento Commands

Run the following commands after adding the module:

php bin/magento setup:upgrade
php bin/magento cache:flush

7. How to Test the Query

Generate Customer Token

mutation {
  generateCustomerToken(email: "test@example.com", password: "Test@123") {
    token
  }
}

Add Header

Authorization: Bearer <customer-token>

Run the Custom Query

{
customerDetails {
id
firstname
lastname
email
}
}

Example Response

{
“data”: {
“customerDetails”: {
“id”: 12,
“firstname”: “John”,
“lastname”: “Doe”,
“email”: “john.doe@gmail.com”
}
}
}

You can check your GraphQL query response by installing the Chrome extension Altair GraphQl.

To check your query, first you have to set the endpoint.

<magento root url>/graphql

Magento uses the GraphQL module to manage all predefined or custom GraphQL queries.

After setting your endpoint, you can see your custom query under the section of document explorer.

Conclusion

In this blog, we covered:

  • What GraphQL is and why it’s better than REST
  • How Magento 2 uses GraphQL
  • How to create a custom GraphQL module
  • How to build a query to get logged-in customer data
  • How to secure GraphQL queries using graphql.xml

This is a common real-world requirement for headless Magento builds, React/Vue storefronts, mobile apps, and PWAs.

Mean, please try the above example, and if you have any queries, then please feel free to put them in the comment section.

Note :- GraphQL included in Magento 2.3.0

. . .

Leave a Comment

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


4 comments

  • rupesh jadhav
    • Subhangi (Moderator)
  • vishal
    • Shubham Sharma (Moderator)
  • Back to Top

    Message Sent!

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

    Back to Home