How to Create Custom GraphQL in Magento 2

Learn how to create a custom GraphQL query in Magento 2 step by step, including schema definition and resolver implementation.

Overview

Magento 2 supports GraphQL for fetching and modifying data. You can create custom GraphQL queries by defining a schema and linking it with a resolver that handles the business logic.

Step-by-Step Implementation

  1. Create a custom module (if not already created).
  2. Add a schema.graphqls file to define your query.
  3. Create a resolver class to handle the query logic.
  4. Register the resolver in your schema.
  5. Test the query using GraphQL tools.

Step 1: Create schema.graphqls


type Query {
    customMessage: String @resolver(class: "Vendor\\Module\\Model\\Resolver\\CustomMessage")
}
    

Step 2: Create Resolver Class


namespace Vendor\Module\Model\Resolver;

use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

class CustomMessage implements ResolverInterface
{
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        return "Hello from Custom GraphQL!";
    }
}
    

Step 3: Module File Structure


app/code/Vendor/Module/
├── etc/
│   └── module.xml
├── registration.php
├── etc/graphql/
│   └── schema.graphqls
└── Model/
    └── Resolver/
        └── CustomMessage.php
    

Step 4: Test GraphQL Query


{
  customMessage
}
    

Expected Output


{
  "data": {
    "customMessage": "Hello from Custom GraphQL!"
  }
}
    

Important Notes

  • Always follow Magento's module structure.
  • Use Dependency Injection for complex logic inside resolvers.
  • You can also create mutations for data updates.
  • Clear cache after adding schema: php bin/magento cache:flush