How To

How to Create Custom GraphQL in Magento 2

Hello Magento Friends,

Today I will be justifying How to Create Custom GraphQL in Magento 2.

GraphQL is a query language for API, that offers customers to exactly fetch the required data while the server returns only the necessary information. GraphQL was introduced in Magento 2.3 as a replacement to REST and SOAP API. GraphQL can be used to read data by query and write data to the server by mutation.

Here are our best extensions that support GraphQL.

Magento 2 SMS Notification Pro

Magento 2 Mobile Login

Here we will discuss How to Create Custom GraphQL in Magento 2. Let’s get started

Steps to Create Custom GraphQL in Magento 2:

Step 1: First, we need to create a “schema.graphqls” file inside our extension at the below path.

app\code\Vendor\Extension\etc\schema.graphqls

Now, add the below code

#Custom Module
type Query
{
    CustomGraphql (
        username: String @doc(description: "Email Address/Mobile Number")
        password: String @doc(description: "Password")
        fieldtype: String @doc(description: "Field Type")
        websiteId: Int = 1 @doc (description: "Website Id")
    ): CustomGraphqlOutput @resolver(class: "Vendor\\Extension\\Model\\Resolver\\CustomGraphql") @doc(description:"Custom Module Datapassing")
}
type CustomGraphqlOutput
{
    username: String
    password: String
    fieldtype: String
}

Step 2: After that, we need to create a “CustomGraphql.php” file inside the below folder path of the extension.

app\code\Vendor\Extension\Model\Resolver\CustomGraphql.php

And add the below code

<?php
namespace Vendor\Extension\Model\Resolver;

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

class CustomGraphql implements ResolverInterface
{
    /**
     * @param Field $field
     * @param \Magento\Framework\GraphQl\Query\Resolver\ContextInterface $context
     * @param ResolveInfo $info
     * @param array|null $value
     * @param array|null $args
     * @return array|\Magento\Framework\GraphQl\Query\Resolver\Value|mixed
     * @throws GraphQlInputException
     */    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null)
    {
        if (!isset($args['username']) || !isset($args['password']) || !isset($args['fieldtype'])||
            empty($args['username']) || empty($args['password']) || empty($args['fieldtype']))
        {
            throw new GraphQlInputException(__('Invalid parameter list.'));
        }
        $output = [];
        $output['username'] = $args['username'];
        $output['password'] = $args['password'];
        $output['fieldtype'] = $args['fieldtype'];
      
        return $output ;
    }
}

You need to test GraphQL Query in Altair GraphQL client chrome extension or you can also test in Postman Software.

The response will be as shown below,

Conclusion:

This way you can Create Custom GraphQL in Magento 2. If you face any difficulty while implementing the above steps let me know via the comment section below. Share the article with your friends and stay connected with us.

Happy Reading!

Click to rate this post!
[Total: 18 Average: 4.4]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

  • Hello @Dhiren,

    Thank you for the post.
    It is very helpful but there is one issue in the below code:

    type Query
    {
    CustomGraphql (
    username: String @doc(description: "Email Address/Mobile Number")
    password: String @doc(description: "Password")
    fieldtype: String @doc(description: "Field Type")
    websiteId: Int = 1 @doc (description: "Website Id")
    ): CustomGraphqlOutput @resolver(class: "Vendor\\Extension\\Model\\Resolver\\CustomGraphql") @doc(description:"Custom Module Datapassing")
    }

    You have to replace "CustomGraphql" with "customGraphql" query name should be stat with a small letter.

    Thanks

Recent Posts

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

2 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

2 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

3 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

6 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

6 days ago