Get a Free Consultation

    Search for:

    Create Custom GraphQL in Magento 2 | Step-by-Step Guide

    Last Updated | November 14, 2023

    In today’s fast-paced e-commerce landscape, having a flexible and efficient way to interact with your Magento 2 store is crucial. This is where GraphQL comes into play. With its ability to request exactly the data you need and nothing more, GraphQL has become a popular choice for developers to build efficient and tailored APIs. In this blog post, we’ll dive into the world of Magento 2 GraphQL and show you how to create custom queries and mutations to better suit your business needs.

    Understanding Magento 2 GraphQL

    What is GraphQL?

    GraphQL is a query language for APIs that allows you to request only the data you need, making it more efficient and versatile compared to traditional REST APIs. It gives clients the power to define the structure of the responses, reducing over-fetching and under-fetching of data.

    Why Choose GraphQL in Magento 2?

    Magento 2 introduced native support for GraphQL, making it an attractive choice for developers. Here are some reasons to opt for Magento 2 GraphQL:

    • Flexibility: Customize data retrieval to match your application’s specific requirements.
    • Efficiency: Fetch only the data you need, improving performance.
    • Scalability: Easily extend and modify your APIs as your business evolves.

    Creating Custom GraphQL Queries in Magento 2

    Step 1: Define Your Query

    The first step in creating custom GraphQL queries is to define what data you want to retrieve. Start by identifying the specific information you need and the object types you want to work with.

    Step 2: Create a Schema File

    In Magento 2, GraphQL schemas are defined in .graphqls files. You’ll need to create a custom schema file where you define your query. For example, if you want to fetch product information, your schema might look like this:

    # app/code/Vendor/Module/etc/schema.graphqls
    type Query {
    customProductQuery(id: Int!): CustomProduct @resolver(class: “\\Vendor\\Module\\Model\\Resolver\\CustomProductQuery”)

    type CustomProduct {
    id: Int
    name: String
    price: Float
    # Add more fields as needed

    Step 3: Implement Resolver

    Next, you’ll need to implement a resolver for your custom query. The resolver is responsible for fetching the requested data and returning it in the required format.

    namespace Vendor\Module\Model\Resolver;
    use Magento\Framework\GraphQl\Config\Element\Field;
    use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
    use Magento\Framework\GraphQl\Query\ResolverInterface;
    use Magento\Framework\GraphQl\Query\Resolver\ValueFactory;
    class CustomProductQuery implements ResolverInterface
    * @var ValueFactory
    private $valueFactory;

    public function __construct(ValueFactory $valueFactory)
    $this->valueFactory = $valueFactory;

    public function resolve(Field $field, $context, $info, array $value = null, array $args = null)
    // Implement your logic to fetch and return the data here
    $productId = $args[‘id’];
    // Perform your data retrieval logic here
    $productData = [
    ‘id’ => $productId,
    ‘name’ => ‘Sample Product’,
    ‘price’ => 29.99,
    // Add more data fields as needed

    $result = function () use ($productData) {
    return !empty($productData) ? $productData : [];
    return $this->valueFactory->create($result);


    Step 4: Test Your Custom Query

    Before using your custom query in a production environment, make sure to test it in the GraphQL Playground or via API calls.

    Creating Custom GraphQL Mutations in Magento 2

    Step 1: Define Your Mutation

    Mutations in GraphQL are used to modify data. To create a custom mutation, start by defining the changes you want to make and the input parameters required.

    Step 2: Create a Schema File

    Similar to custom queries, you need to create a schema file for your custom mutation. Define the mutation and the expected input and output types.

    # app/code/Vendor/Module/etc/schema.graphqls
    type Mutation {
    updateProductQuantity(input: UpdateProductQuantityInput!): UpdateProductQuantityOutput @resolver(class: “\\Vendor\\Module\\Model\\Resolver\\UpdateProductQuantity”)

    input UpdateProductQuantityInput {
    productId: Int!
    newQuantity: Int!

    type UpdateProductQuantityOutput {
    success: Boolean
    message: String


    Step 3: Implement Resolver

    Create a resolver for your custom mutation to handle the data modification. This resolver should include the necessary business logic to make the changes you defined.


    namespace Vendor\Module\Model\Resolver;
    use Magento\Framework\GraphQl\Config\Element\Field;
    use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
    use Magento\Framework\GraphQl\Query\ResolverInterface;
    use Magento\Catalog\Api\ProductRepositoryInterface;
    use Magento\Catalog\Model\Product;

    class UpdateProductQuantity implements ResolverInterface
    private $productRepository;

    public function __construct(ProductRepositoryInterface $productRepository)
    $this->productRepository = $productRepository;

    public function resolve(Field $field, $context, $info, array $value = null, array $args = null)
    $productId = $args[‘input’][‘productId’];
    $newQuantity = $args[‘input’][‘newQuantity’];

    try {
    /** @var Product $product */
    $product = $this->productRepository->getById($productId);
    $product->setStockData([‘qty’ => $newQuantity, ‘is_in_stock’ => $newQuantity > 0]);

    return [‘success’ => true, ‘message’ => ‘Product quantity updated successfully.’];
    } catch (\Exception $e) {
    return [‘success’ => false, ‘message’ => $e->getMessage()];


    Step 4: Test Your Custom Mutation

    Thoroughly test your custom mutation to ensure it performs as expected and makes the desired changes.

    Frequently Asked Questions

    1. Can I use custom GraphQL queries and mutations to optimize my store’s performance?

    Absolutely! By tailoring your data requests to only what is needed, you can significantly improve your store’s performance and reduce server load.

    2. Are there any security considerations when creating custom GraphQL endpoints?

    Security is paramount. Always validate and sanitize user input and consider implementing authentication and authorization mechanisms to protect your GraphQL endpoints.

    3. How do I handle errors in custom GraphQL queries and mutations?

    Implement error handling in your resolvers to provide meaningful error messages and gracefully handle unexpected situations.

    4. Can I use third-party GraphQL tools and libraries with Magento 2?

    Yes, you can use third-party tools and libraries to enhance your GraphQL development experience in Magento 2. Popular options include Apollo Client and GraphQL Yoga.

    In conclusion, custom GraphQL queries and mutations empower you to optimize your Magento 2 store’s performance and provide tailored experiences to your customers. By following the steps outlined in this guide, you can create custom GraphQL endpoints that perfectly align with your business requirements and improve the efficiency of your e-commerce platform. Don’t hesitate to leverage the flexibility and power of GraphQL in Magento 2 to stay ahead in the competitive e-commerce landscape.




    Meet Naveed Abbas, a seasoned web developer with 10+ years of experience. Specializing in PHP, Magento 2, WordPress, Laravel, and APIs, Naveed is your go-to expert for crafting digital solutions that stand out. With a passion for staying ahead in the ever-changing tech world, he ensures your projects are not just up to date but tailored to your unique needs. Join Naveed on a coding journey where innovation and expertise meet simplicity and excellence.