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 Magento 2 use and provide an example of creating an endpoint.
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 speeding up and boosting the APIs, their flexibility, and their effectiveness.
A couple of things to know about this syntax:
- It is capable of retrieving only that data which 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 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. Such advanced eCommerce PWA sites (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 Magento PWA development costs.
When a user opens a page on the PWA for the first time, a request to the server is made for receiving 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 data. This is indicated when building the GraphQL schema 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 that developers can build these requests in such 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 Magento PWA developers 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 Magento site’s performance improves and consequently becomes much better. Moreover, users receive precisely what they were searching for much faster and right to the point.
In order to be certain that the schema will deliver what was expected, developers can check the string.
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 towards clients. By giving clients the 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 nor 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, 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 Magento PWA developers 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: Wikipedia
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:
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 building progressive web applications.
For instance, developers often use the PWA Studio to build PWAs (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 Magento PWA examples 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, for Magento PWA GraphQL is a great fit for the API side of the work. 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 front end 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).
As of now, the GraphQL feature set is capable of covering the major points that are vital for building front-end solutions for headless Magento and PWAs (you can read more about headless commerce in our guide). Currently, 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, 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.
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.
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).
Naming some of its weak points and disadvantages, as well as the GraphQL functionality which is missing:
1) GraphQL modules are a big question. Since GraphQL is rather new, and the ecosystem isn’t that extensive yet, a plethora of modules (including those for Magento) is missing GraphQL by default. Thus, there’s a lot of custom coding involved as well as front-end work if you’re developing a PWA. 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.
Let’s take the popular payment method that’s used in Australia, Afterpay, as an example. Although the module includes server-side solutions for regular payment data pull, it doesn’t provide GraphQL solutions. So, to get data from the front end, you’ll need your own custom GraphQL.
There’s a similar situation with wishlist and client reviews functionality. By default, you can view items that have already been added to a wishlist or read the given customer feedback on a specific product. But it is currently not possible to take action (like add/delete an item from the wishlist or submit a client review) via the existing GraphQL solutions.
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.
4) The design and maintenance of a large and complex schema may be challenging.
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:
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 module that’ll be used. In our case, it is called CountNumberDays. We’ll need to create two files:
- Create a registration.php file
- Create an etc/module.xml file
Step 2: Creating a new endpoint (Magento Graphql example)
In order to make an 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 on 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 it being 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.
2) Define the schema (query or mutation)
In this step, you should define and describe the schema of possible queries.
- Query Name:
- Indicate parameters which month and year:
- Indicate output data:
- Describe the file path that’ll process the query:
- Add a description:
- 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.
- Add entity cache to the GraphQL schema:
As a result, we get a schema in which we describe the type 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:
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.
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 the Altair GraphQL, to name a few).
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 as a complete and decisive replacement for REST, yet it is a wonderful fit for various use cases in Magento front-end development, including PWAs.