Open menu
Magento GraphQL: Overview and How to Use Guide

Magento GraphQL: Overview and How to Use Guide

Magento GraphQL: Overview and How to Use Guide

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.

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 speeding up and boosting the APIs, their flexibility, and their effectiveness.

A couple of things to know about this syntax:

  1. 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). 
  2. Unlike its older analogs (such as REST), GraphQL offers a smarter approach to working with data and is a lot faster than its substitutes.
  3. Interestingly, GraphQL depends on the data and the code that’s behind it, thus, it isn’t linked to a 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 websites (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 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 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.

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 performance 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. 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

How Does GraphQL Differ From REST or SOAP API?

In a nutshell, all three are used for web 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.

The bottom line is that GraphQL is a lot more flexible, doesn’t lag behind the client requirements that change quite quickly, and allows developers to create APIs in whichever preferred methods without the necessity to exclude fields nor affect the queries that already exist.

The biggest difference between REST, SOAP API, and GraphQL lies in the capability of the latter 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 with the purpose of achieving the same results (and most likely these results won’t be as precise as the ones provided by GraphQL).

GraphQL is also attractive as a query language due to its approach towards clients. By giving clients the data control, it gives them the opportunity to determine what data should be received in the response. Unlike the general server-driven approach of REST that often delivers too much or too little information or pitches those results that were unrelated to the initial query (which only triggers additional queries).

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 building progressive web applications. For example, the PWA Studio (an official set of tools that’s utilized by developers for creating progressive web applications on Magento) uses GraphQL.

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:

  1. queries (for reading and receiving information),
  2. mutations (needed for taking actions, creating data, and changing information, f.e. a customer’s email),
  3. 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).

Major GraphQL Achievements in Magento: What’s Been Done

As of now, the GraphQL feature set is capable of covering the major points that are vital for building front-end solutions on Magento. Currently, the latest version of Magento is equipped with such a set of GraphQL features:

  1. The support of all kinds of products,
  2. 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),
  3. The support of various types of shipping methods,
  4. Enhanced layered navigation with advanced features and new design,
  5. Reached a standard response time of below 0.5 seconds with five hundred simultaneous requests.

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.

Which GraphQL Functionality Is Missing?

Unfortunately, not all aspects and scenarios have ready-made GraphQL solutions as of now. This means that there are things you will need to develop by yourself (most likely from scratch).

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. I.e., any module that you plug into Magento that doesn’t have included GraphQL capabilities will require custom GraphQL development, as well as front-end work from scratch (if you’re developing a PWA). Sadly, many modules are missing the functionality since GraphQL is rather new and the ecosystem isn’t that extensive yet.

An example of such could be the case with the popular payment method that’s used in Australia called Afterpay. Although the module includes server-side solutions for regular payment data pull, it doesn’t provide GraphQL solutions by default. Therefore, to get data from the front end, you’ll need to create your own custom GraphQL.

There’s a similar situation with wishlist and client review functionality too. Although by default you can view items that have already been added to a wishlist or read the given customer feedback on a specific product, it is currently not possible to take action (like adding/deleting an item from the wishlist or submitting a client review) via the existing GraphQL solutions. You’ll have to create such additional GraphQL functionality yourself.

GraphQL FAQ

What’s the difference in GraphQL authorization and authentication? 

Since the two are at times mixed up it is vital to understand that the process of authorization deals with the rules that grant permission rights for access whereas authentication revolves around confirming identity.

Authorization is customarily carried out not with GraphQL, it is recommended to do this with the help of business logic that’s responsible for data access. When implemented in GraphQL, authentication, on the other hand, could be handled using patterns like OAuth.

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 nesting where applicable.

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

magento graphql

Can you use GraphQL offline?

Unfortunately, no, GraphQL doesn’t support the usage that isn’t online yet due to the lack of built-in web caching. As of now, the problem is sometimes solved by building libraries on top.

Does GraphQL have disadvantages?

It is more than fair to state that although GraphQL has many strong sides, it isn’t almighty. Naming some of its weak points:

  • Not all modules (including those for Magento) have default GraphQL functionality, thus, there’s a lot of custom coding involved.
  • GraphQL isn’t available offline due to the absence of default support for network caching.
  • The design and maintenance of a large and complex schema may be challenging.
  • GraphQL lacks file uploading functionality (unlike REST that’s capable of processing various content types).

Magento 2 Graphql Example of Creating a New Endpoint

Now let’s move on to our short Magento 2 GraphQL tutorial of creating a new endpoint. 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).

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:

Step 2: Create a file

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

Step 3: Define the schema (query or mutation)

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

  1. Query Name:

  2. Indicate parameters which month and year:

  3. Indicate output data:

  4. Describe the file path that’ll process the query:

  5. Add a description:

As a result, we get:

Step 4: Schema’s resolver

Step 5: 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).

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 as a complete and decisive replacement for REST, yet it is a wonderful fit for various use cases in Magento front end development, including PWA.

Related Articles

Magento tips from real projects
Magento tips from real projects
Close
CALL US 24/7:
Australia
& asia
+61 (02) 8005-7494