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.
Table of Content
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.If you want more specific examples, read about
, a Finnish-based tour operator offering group excursions. It was one of our first projects where we created a Magento PWA. When working on this website, we implemented the best practices to improve user experience and performance, and the transition to headless architecture was the most significant decision.Such advanced
(that are “pretending” that they’re applications) are noted for the following characteristics:- being lightning-quick;
- mobile-friendly;
- intuitive to use;
- available offline;
- budget-saving;
- worthwhile 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 a server/client data mismatch to superfluous
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
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:
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:
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:
- Functionality for handling cases with reorders,
- Preferred payment methods that were saved,
- Data on the order history of those customers who’ve logged in,
- Information regarding messages and packing gifts,
- Inventory management cases for collecting items in stores,
- 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.
- 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. - 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.
- 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.
- 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.
40 Hours of Magento Services. FOR FREE
Try our custom development, optimization, support, and design services. One week, free of charge, no strings attached.
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:
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
.