Table of Content

Magento GraphQL: Overview and How to Use Guide (Updated 2024)

Magento GraphQL

There are many approaches to working with APIs, yet GraphQL has shown many of its strengths that can be used to your advantage. 

In this article, we'll introduce you to GraphQL, how it differs from its analogs, and to Magento 2 GraphQL use cases. We'll go over what was already done and bring up which imperfections and challenges can be faced when working with it. What is more, we'll give answers to some of the often-asked questions regarding GraphQL in Magento 2 and provide an example of creating an endpoint.

What Is GraphQL?

Used for application programming interfaces (or APIs), GraphQL is a query language and server-side runtime that was created back in 2012-2015 by Facebook. Its major aim is to speed up and boost the APIs, their flexibility, and their effectiveness.

A couple of things to know about this syntax:

  • It is capable of retrieving only the data the user has requested in just one call (as opposed to providing the entire scope in several queries). 
  • Unlike its older analogs (such as REST), GraphQL offers a smarter approach to working with data and is a lot faster than its substitutes.
  • Interestingly, GraphQL depends on the data and the code that's behind it; thus, it isn't linked to storage or a database.

How GraphQL Works

To give a simple explanation of how it works, let's take a PWA (progressive web app) with client-side rendering as an example case.

  • For reference, PWAs are websites that are designed to function just as a native application would, yet with the UX of a full-scale app. For implementations, you can visit our article with an overview of the most outstanding websites. The companies on this list demonstrate how they reap the benefits of transforming their stores into PWAs in terms of design and performance. Such advanced (that are “pretending” that they’re applications) are noted for being lightning-quick, mobile-friendly, intuitive to use, available offline, budget-saving, and worth the money in terms of .

When a user opens a page on the PWA for the first time, a request to the server is made to receive general website information. Then, after the initial load, as the user starts browsing the website and moving from page to page, GraphQL fetches only those pieces of data that were requested (instead of delivering the entire data scope).

This is done via a schema that's predefined. As a result, the user receives information on their screen very quickly since GraphQL extracts only request-specific data. It shows just the part that's asked (contrary to pulling back all the available data). Therefore, this tremendously cuts down the waiting time for the delivered data.

The syntax that's responsible for fulfilling the process outlines the way how the request inquires for data. This is indicated when building the GraphQL with SDL (Schema Definition Language). Schemas define which objects on the server may be queried, their fields, what could be requested, which data can be retrieved, as well as what kind of relationships the objects have. This means developers can build these requests in a way that allows extracting only the necessary data from more than one source in as little as one API call.

When creating your first GraphQL schema, you may face many challenges, from server/client data mismatch to superfluous database calls. These issues can make your app slow and unresponsive. If you want to take full advantage of GraphQL features and build a fast store with an epic customer experience and zero bugs, turn to our to get things right the first time.

Therefore, by opting for GraphQL, it becomes possible to specify the exact data that's expected from the server side. And since the number of server queries is reduced to the minimum, the and consequently becomes much better. Furthermore, the enhancement ensures that users quickly and efficiently find exactly what they are looking for.
In order to be certain that the schema will deliver what was expected, developers can check the string.

How Does GraphQL Differ From REST or SOAP API?

In a nutshell, all three are used for APIs, yet the architecture that's used by REST or by the SOAP protocol is less advanced than GraphQL. Furthermore, GraphQL provides solutions for common occurring imperfections and flaws of its two older alternatives that developers often come across.

1. API architecture

The REST API's architecture is conceptually different from the Graphql one. The main difference is that in REST, the client can only receive the data that the server provides. In essence, the user doesn't have the possibility to request the necessary data they need, in this case.
Being a query language, GraphQL is capable of obtaining and passing on just the necessary data from the server, not the full scope.

2. Number of queries & endpoints

One more major difference between REST, SOAP API, and GraphQL lies in the capability of GraphQL to obtain clean-cut results in a single call, as it needs only one endpoint.
REST, on the other hand, normally requires more than one query-send to multiple endpoints in order to achieve the same results (and most likely, these results won't be as precise as the ones provided by GraphQL).

3. Client-driven vs. server-driven approach

GraphQL is also attractive as a query language due to its approach toward clients. By giving clients data control, they have the opportunity to determine what data should be received in the response. So, GraphQL doesn't lag behind the client requirements that change quite quickly.
On the other hand, REST has a general server-driven approach. It often delivers too much or too little information or pitches those results that were unrelated to the initial query (which only triggers additional queries).
The bottom line is that GraphQL is a lot more flexible and allows developers to create APIs in whichever preferred methods without the necessity to exclude fields or affect the queries that already exist.
While GraphQL is both powerful and flexible, its adoption can't be without challenges. How to handle errors, pagination, caching, authentification, and authorization are just a few of the cross-cutting issues businesses face on their implementation journey. These problems aren't unique to GraphQL, but they can feel more challenging than with REST or SOAP. Contact our to make your GraphQL journey smooth.

4. What REST & GraphQL queries look like

This is how a REST query to Magento looks like with a response:

REST query example

Image credit:

Below is a Magento 2 GraphQL query example of how an existing product's ID, name, categories, URL, and SKU data are shown in the GraphQL response:

Magento GraphQL query example

What Is GraphQL Needed for in Magento 2? 

Answering the question of how to use GraphQL in Magento 2 and what it's for, the main use of GraphQL in Magento is for .

For instance, developers often use the (it is an official set of tools that’s utilized for simplifying the process of creating progressive web applications on Magento, it includes ready-made GraphQL solutions). You can check out some to get a better understanding of what such sites are like.

Because “Magentitians” aspire to use those solutions that'll be efficient, time-optimal, and flexible, GraphQL is a great fit for the API side of the work (together with and other tools). And since Magento is a highly loaded system in itself, GraphQL is handy for “unloading” it. I.e., by indicating the return of the results based on the required field with GraphQL and for replacing SOAP and REST in frontend development. Although not all default query cases are covered yet, the main functionality is already available.

That said, there are only three main operations of GraphQL that are in use:

  • queries (for reading and receiving information);
  • mutations (needed for taking actions, creating data, and changing information, f.e. a customer's email);
  • subscriptions (this operation isn't available in Magento yet, but it provides the opportunity to get data from the server in real-time automatically after a while, for instance, for notifications).

GraphQL in Magento: Major Achievements

As of now, the GraphQL feature set is capable of covering the major points that are vital for building frontend solutions and PWAs (you can read more about in our guide). The latest version of Magento is equipped with such a set of GraphQL features:

  • The support of all kinds of products;
  • The support of default payment options and methods (these include PayPal, Check Money, Bank Transfer, Payment on Account, Cash on Delivery, and Braintree, to name a few);
  • The support of various types of shipping methods;
  • Enhanced layered navigation with advanced features and new design;
  • Reached a standard response time of below 0.5 seconds with five hundred simultaneous requests;
  • Functionality for handling cases with reorders;
  • The possibility to save tokens for making card payments without re-entering data;
  • Data on the order history of those customers who've logged in;
  • Information regarding gift messages and gift wrapping in orders;
  • Different inventory management cases;
  • One universal mutation capable of processing every product type;
  • A wish list and client review functionality.

What’s Planned to Be Done: GraphQL Roadmap

Of course, a lot is still to be accomplished so as to expand the features and capabilities of GraphQL for the use in Magento. For the time being, the roadmap includes not only fixing bugs but also finalizing the solutions that would be suitable for B2C use cases. That said, among the points that are in the main focus include:

  1. Functionality for handling cases with reorders,
  2. Preferred payment methods that were saved,
  3. Data on the order history of those customers who’ve logged in,
  4. Information regarding messages and packing gifts,
  5. Inventory management cases for collecting items in stores,
  6. Adding one universal mutation (that’s capable of processing every product type) to substitute mutations that handle the placement of items in a cart based on a specific product.

Of course, some work still has to be done to expand the features and capabilities of GraphQL in Magento. But the lacking solutions are being constantly developed, so there are fewer blind spots by the year.

GraphQL in Magento: Disadvantages & Missing Functionality

It is more than fair to state that although GraphQL has many strong sides, it isn't almighty. Unfortunately, as of now, not all aspects and scenarios have ready-made GraphQL solutions. This means that there are things you will need to develop by yourself (most likely from scratch). Let's see what some weak points of GraphQL are.

  1.  GraphQL modules. Actually, as of 2023, Magento has covered almost all its functionality through GraphQL. Furthermore, many third-party module vendors began to make their products GraphQL-compatible (in other words, provide ready-made GraphQL API). However, oftentimes those APIs are of poor quality, and writing one from scratch is a better idea.
    Since GraphQL is rather new, and the ecosystem isn't that extensive yet, many modules (including those for Magento) include only server-side solutions for regular payment data pull and are still missing GraphQL by default. Thus, custom coding is inevitable, as well as frontend work if you're developing a . In short, any module (especially if it's a custom one) that doesn't have GraphQL functionality yet will have to be created from square one.
  2. Likewise, GraphQL lacks functionality. For example, this regards file uploading functionality (unlike REST, that's capable of processing various content types). You'll have to create such additional GraphQL functionality yourself.
  3. GraphQL isn't available offline due to the absence of default support for network caching. But, when creating progressive web apps, you can configure PWA’s offline functionality on the client side, bypassing this GraphQL drawback.
  4. The design and maintenance of a large and complex schema may be challenging. But it's fair to say this statement is applicable to any large API. This and some other intricacies of GraphQL in Magento are successfully handled by seasoned web developers.

How Do You Create a GraphQL Mutation?

As mentioned earlier, a mutation is an operation that's used when we'd like to take action. When building the mutation, it is advised to be careful with naming, to be precise about the mutation's specifics, to be careful with the unique object and payload type that are input, as well as to apply to the nest where applicable.

Below is an example of creating a GraphQL mutation for a customer profile:

Example of a Magento GraphQL mutation for a customer profile

Magento 2 GraphQL Tutorial

Mentioning what will be required for GraphQL implementation, Magento's 2.4 version is already fitted with GraphQL support.
In this part of the guide, we'll go over the process of implementing GraphQL in Magento step by step. We'll provide an example of creating a new module that'll have a GraphQL endpoint.

Step 1: Create GraphQL module in Magento 2

The first thing that needs to be done is creating a new GraphQL module that'll be used. In our case, it is called CountNumberDays. We'll need to create two files:

  • Create a registration.php file
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="MyModule_CountNumberDays" setup_version="1.0.0">
 		<sequence>
 		</sequence>
	</module>
</config>
  • Create an etc/module.xml file
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
   \Magento\Framework\Component\ComponentRegistrar::MODULE,
   'MyModule_CountNumberDays',
   __DIR__
);

Step 2: Creating a new endpoint (Magento Graphql example)

In order to make an GraphQL endpoint, you can use either the browser or, for convenience, an integrated development environment (short for IDE). Below, we'll walk you through the steps of creating an endpoint on a server in GraphQL as an example.

Let's assume that we would like to receive information regarding the number of days that an indicated month has in a specified year (regardless of whether it is a leap year or not).

1) Create a file with a GraphQL schema

Next, you need to create a file like in the example below. Note that the etc/schema.graphqls part is obligatory. 

CountNumberDays/etc/schema.graphqls

2) Define the schema (query or mutation)

In this step, you should define and describe the schema of possible queries.

  • Query Name:
getCountNumberDays
  • Indicate parameters which month and year:
input DateInput {
 year: Int
 month: Int
}
  • Indicate output data:
type DateOutput {
 days: Int
}
  • Describe the file path that’ll process the query:
MyModule\\CountNumberDays\\Model\\Resolver\\GetCountNumberDays
  • Add a description:
@doc(description: "Find the number of days that a month has in the specified year")
  • Add an identity class. Our resolver will use the entity class to tag values. Plus, later on, when it'll come back for this data, it will use the resolver cache instead.
<?php
declare (strict_types = 1);
namespace MyModule\CountNumberDays\Model\Resolver\Navigation;
use Magento\Framework\GraphQl\Query\Resolver\IdentityInterface;
class Identity implements IdentityInterface
{
   /** @var string */
   private $cacheTag = "my_module_count_number_days";
   /**
    * Get PromoBanners identities from resolved data
    *
    * @param array $resolvedData
    * @return string[]
    */
   public function getIdentities(array $resolvedData): array
   {
       return [ $this->cacheTag ];
   }
}
  • Add entity cache to the GraphQL schema:
@cache(cacheIdentity: "MyModule\\CountNumberDays\\Model\\Resolver\\GetCountNumberDays\\type QueryIdentity")

As a result, we get a schema in which we describe the type of Query and the resolver class for the endpoint. Plus, we added the cache. Here's what the full app code of this block looks like:

type Query {
   getCountNumberDays(input: DateInput): DateOutput 
     @resolver(class: "MyModule\\CountNumberDays\\Model\\Resolver\\GetCountNumberDays") 
     @cache(cacheIdentity: "MyModule\\CountNumberDays\\Model\\Resolver\\GetCountNumberDays\\Identity")
     @doc(description: "Find the number of days that a month has in the specified year")
}

input DateInput {
   year: Int
   month: Int
}

type DateOutput {
   days: Int
}

Step 3: Schema’s resolver

This is our resolver that will handle part of the getCountNumberDays request that's related to the identity described in point f) of the previous step.

<?php
declare(strict_types=1);

namespace MyModule\CountNumberDays\Model\Resolver;

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

class GetCountNumberDays implements ResolverInterface
{
   /**
    * @inheritdoc
    */
   public function resolve(
       Field $field,
       $context,
       ResolveInfo $info,
       array $value = null,
       array $args = null
   ) {
       if (!isset($args['input']['month']) || !isset($args['input']['year'])) {
           throw new GraphQlInputException(__('Month or Year not indicated'));
       }
       
       return [
           'days' => cal_days_in_month(CAL_GREGORIAN, $args['input']['month'], $args['input']['year'])
       ];
   }
}

Step 4: Check that query & response

The final step is about making sure that the query is mistake-free and gives proper responses. This can be done via one of the many readily available extensions (such as ChromeiQl, GraphiQL, or Altair GraphQL, to name a few).

Final Say

Summing up, GraphQL has many strong sides indeed. It's fast, flexible, provides accurate data in responses, and is a great alternative to its earlier analogs. Of course, it can't be considered a complete and decisive replacement for REST, yet it is a wonderful fit for various use cases in Magento frontend programming, including .

Related Articles

Headless Commerce: the Definitive Guide for Business Leaders
Art Malkovich
Art Malkovich, Onilab CEO

Headless Commerce: the Definitive Guide for Business Leaders

15 min
Jul 29, 2023
How to Develop a Store Using Magento PWA Studio (Updated for 2024)
Alex HusarDmitry Gayduk
Two authors, Onilab LLC

How to Develop a Store Using Magento PWA Studio (Updated for 2024)

30 min
Aug 5, 2023
How to Build a PWA Storefront for Magento 2 in 2024: A Detailed Guide
Alex Husar
Alex Husar, Onilab CTO

How to Build a PWA Storefront for Magento 2 in 2024: A Detailed Guide

30 min
Jul 20, 2023
Magento 2 Speed Optimization: 32 Effective Fixes (Updated 2024)
Alex Husar
Alex Husar, Onilab CTO

Magento 2 Speed Optimization: 32 Effective Fixes (Updated 2024)

21 min
Jul 6, 2023

FAQ

Does Magento use GraphQL?

Yes, Magento GraphQL support began in the 2.3 version, which hugely facilitated transforming traditional monolithic stores into progressive web apps. Of course, you need to create custom GraphQL queries, but the number of ready-made GraphQL solutions is steadily expanding.

How to use GraphQL in Magento 2?

This data query language and runtime has proven to be highly efficient and convenient for creating PWAs. In progressive web apps, the backend and frontend are decoupled and connected via an API guaranteeing faster page loading and giving more flexibility in the frontend development. Using exactly GraphQL further accelerates a PWA store operation.

What is the difference between REST API and GraphQL in Magento 2?

Unlike those created with traditional SOAP or REST API, Magento GraphQL queries are more precise, fast, and save server resources. Importantly, we make fewer GraphQL queries to fetch exactly what's needed because different data types can be requested in one call.

Let’s stay in touch

Subscribe to our newsletter to receive the latest news and updates.