Creating Custom GraphQL in Magento 2

What is GraphQL in Magento 2?

GraphQL in Magento 2 is an API query language that allows clients to request exactly the data they need. Unlike REST APIs, GraphQL enables fetching multiple resources in a single request, making it highly efficient for modern frontend frameworks such as PWA Studio, React, and Vue.

Magento provides a flexible GraphQL framework where developers can create custom queries, mutations, and resolvers to expose custom business logic or module data.

Main Components Required for Custom GraphQL

To create a custom GraphQL API in Magento 2, the following components are required:

  • schema.graphqls → Defines GraphQL query structure.
  • Resolver → Handles business logic and returns data.
  • Dependency Injection → Registers resolver classes.
  • Module Structure → Proper Magento module setup.

Step 1: Create schema.graphqls

This file defines the GraphQL query and response structure.

(File: app/code/VendorName/ModuleName/etc/schema.graphqls)




This schema defines a custom query called customProductMessage that returns product information with a custom message.

Step 2: Create GraphQL Resolver

The resolver contains the logic that runs when the GraphQL query is executed.

(File: app/code/VendorName/ModuleName/Model/Resolver/CustomProductMessage.php)




The resolver fetches the product using Magento's ProductRepository and returns a custom response.

Step 3: Register Resolver (Optional DI Configuration)

Magento automatically detects resolvers defined in schema.graphqls, but you can still configure dependencies if needed.

(File: app/code/VendorName/ModuleName/etc/di.xml)




Example GraphQL Query

You can test the query using GraphQL Playground or Magento's GraphQL endpoint.




Example Response:




Best Practices for Magento 2 GraphQL Development

  • Use Service Contracts instead of direct model usage.
  • Validate input arguments to prevent errors.
  • Use Data Providers for complex business logic.
  • Implement GraphQL caching when possible.
  • Use mutations for write operations (create/update/delete).