What is Graphql and How to Implement in Magento2

What is Graphql and How to Implement in Magento2

What is GraphQL?

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. It provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

It was developed by Facebook, which first began using it for mobile applications in 2012

Application Components

  • Server Side Components
  • Client Side Components

Server Side components

  • Schema : A GraphQL schema is at the center of any GraphQL server implementation and describes the functionality available to the clients which connect to it.
  • Query : A GraphQL query is the client application request to retrieve data from database or legacy API’s.
  • Resolver : Resolvers provide the instructions for turning a GraphQL operation into data. They resolve the query to data by defining resolver functions.

Client Side Component

  • GraphiQL : Browser based interface for editing and testing GraphQL queries and mutations.
  • ApolloClient : Best tool to build GraphQL client applications. Integrates well with all javascript front-end.

Type System

GraphQL is a strongly typed language. Type System defines various data types that can be used in a GraphQL application. The type system helps to define the schema, which is a contract between client and server

  1. Scalar : Stores single value
  2. Object : Shows what kind of object can be fetched
  3. Query : Entry point type to other specific types
  4. Mutation : Entry point for data manipulation
  5. Enum : Useful in a situation where you need the user to pick from a prescribed list of options

Query Type

It is used to fetch Data same as in rest api we are using GET method to fetch data

type Query
{
    getCustomer (
        username: String
         
    ): getCustomerOutput
}

Mutation Type

It is used to create/update/delete data , Same as POST/PUT/DELETE in rest api

type Mutation {
   addCustomer(name: String, email: String): Customer
}

How to Implement in Magento2 ?

First of all, you need to create module, If you are new in magento and don’t know how to create custom module, you can visit our previous topic.

Now you need to create schema.graphqls under etc folder and add 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: "MageAcademy\\GraphQlExample\\Model\\Resolver\\CustomGraphql") @doc(description:"Custom Module Datapassing")
}
type CustomGraphqlOutput
{
    username: String
    password: String
    fieldtype: String
}

Here you can see Resolver class, which is used to implement Business logic.

You can create Resolver class under Model/Resolver/CustomGraphql.php

<?php
namespace MageAcademy\GraphQlExample\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 ;
    }
}

How to test your graphql?

As I mentioned above in Client Side Component you can use graphiql or alternatively you can use postman as well to test

Watch our video on graphql in hindi

Hope you like our topic. Please share with your friends and write us comment if any doubt.

Visit again.

Subscribe to our newsletter

Leave a Reply
Your email address will not be published. *