What is GraphQL?
In this article, we discuss everything that is happening with GraphQL and how the technology can transform the way your business builds web applications.
I could simply tell you that it is a programming language designed by Facebook — and I would not be wrong — but you could find out just as much by reading its Wikipedia page. To understand the importance of GraphQL, it is essential to examine it in the right context.
Templates
As the applications we rely on become ever more complex, the desire to separate how they function from how they look grows stronger. Years ago — and I mean years ago (back in the 1990s) — it was common for each platform to handle its own backend and also render its entire user-facing interface. This was the simplest solution, even if customisation quickly became a challenge. Modifying the appearance directly in the code meant the application could no longer be easily upgraded, so various templating solutions were devised.
Some systems opted for templates written in the same programming language used by the surrounding platform. This is how WordPress-based systems work to this day, with the template being the main logic loop. It mixes the code responsible for drawing the user interface (HTML) with logic that fetches data from the database and runs any required plugins.
Others chose to use domain-specific languages (special languages created to solve a particular problem) to describe the look, with the platform interpreting them when rendering a response. There is a good chance this is how your Magento-based shop is built today.
The first approach has the disadvantage that programmers modifying the template must be full-stack developers with a solid understanding of both backend logic (including its language of choice) and the languages used to build the interface (e.g. HTML, CSS, JavaScript). Since the template itself acts as the main logic loop, it inadvertently affects business logic, while modifying the appearance becomes a risk that must be tested specifically. The page may look as it should, but what if the programmer forgets to include the call to your tax service?
The latter approach means your frontend engineers would likely need to learn a new language, and much of their knowledge would be platform-specific. While breaking business logic becomes much harder, at some point your organisation starts hiring Magento theme developers instead of frontend engineers. A candidate's extensive knowledge of modern frontend frameworks will be irrelevant unless they learn how to create a theme for the platform.

Interlude: servers and APIs
For two pieces of software to communicate, they need to know how to exchange information and how to interpret the data the other party may choose to transmit. There are standards describing particular use cases, languages, and protocols that dictate how programmes talk to each other.
Typically, the party with an established address is called the server, and the party connecting to it is called the client. For communication to begin, the client must reach out (connect) to the server. Think of it as a hungry customer walking into a restaurant — there is simply no way for a waiter to know where all the hungry people in the city are.
A communication standard intended for programmatic consumption is called an Application Programming Interface (an API), and an address of a server implementing that standard is called an API endpoint. When a web browser connects to a web server, it uses its HTTP API (Hypertext Transfer Protocol, which powers the Web) by connecting to its HTTP endpoint at the address you provided in the address bar.
AJAX
Both templating solutions mentioned have their individual limitations beyond those listed above, but the most glaring flaw is that they were developed at a time when everything was rendered by the server. If every user action requires a round-trip to the server, there is no way to support offline mode. If every interaction requires redrawing the entire page, how do you implement live search across a catalogue of five million products?
This is how we arrived at hybrid solutions where most of the layout would be server-rendered, but another — asynchronous — method allows the user interface to fetch additional data as needed. This is where AJAX (Asynchronous JavaScript and XML) first appeared. While AJAX was more of a concept than a standard, it offered a way to fetch snippets of HTML (or XML if you insisted on staying true to its name) and then add them to the already-rendered page.
AJAX made it possible to implement new types of website elements, but as there was no standardised method for doing so, developers at different companies (and sometimes in different rooms in the same office) had very different opinions on how everything should work. Eventually, server-to-server communication was largely standardised around a specification called Simple Object Access Protocol (SOAP), while browser-to-server communication settled on Representational State Transfer (REST).
Interlude: resources and procedures
SOAP and REST each take a very different approach to interface design.
SOAP is a remote procedure call (RPC) mechanism. It proposes a list of predefined operations — the "procedures" — each procedure accepting a predefined number of parameters and returning a number of named values of predefined types. A hypothetical addition procedure might accept two parameters, a and b, of type number, and return a single named value sum, also of type number.
REST is an API built around resources. Each resource represents either a single entity or a collection of entities of a particular type. Each resource supports a number of operations: create, read, update, and delete. A hypothetical collection of book resources might contain a single resource representing The Little Prince by Antoine de Saint-Exupéry. We could then update it with the publication year, an international standard book number, and later ask the resource to return the information to us.
Single-page applications
Building dynamic interfaces with AJAX was a pain. This was because the code for drawing the same parts of the user interface had to live on both the server side and the client side — the first version would be generated by the server and sent to the browser. Then, when the user interacted with the page, certain parts would need to be redrawn by JavaScript code running in the browser. Whenever visual changes were made, they had to be made in both places, potentially requiring different skill sets for each part. Hardly an ideal solution. Recent years have given rise to a new type of frontend framework: one where the entire application is rendered by JavaScript in the browser. The server no longer needs to prepare the initial version of the page, in what are known as single-page applications (SPAs).
Applications written in React, Vue.js, or Angular do not use any outdated templating solutions implemented by the server. The headless server architecture (since servers no longer have a user interface) with rich clients allows frontend engineers to build the entire user experience using technologies they know and in languages of their choice. Updating the text on your about page no longer requires a backend developer — but as everything becomes API-driven, the architectural choices behind the API become the limiting factor for team performance.
SOAP did a great many things well, but in doing so it required a very complex representation for any information transferred, which made it difficult for JavaScript programmers to work with. REST's insistence on treating object states rather than state transitions means there is no obvious way to represent abstract concepts that do not map directly to tangible objects.
To understand the limitations of REST, imagine an API representing the apples I hold. Each time a friend of mine uses the app to claim one of my apples, I want to decrease the number of available apples.
A naive solution would be to introduce a "me" resource with a field containing the current number of apples to hand. However, since reading and writing are separate operations, there is no safe way to decrease the number by one without risking what is known as a race condition — the case where two clients read a value and then both attempt to modify it, thereby undoing each other's actions. Assuming there are 5 apples to start with, both clients would read the number 5 and then post an update, both setting the count to 4.
In practice, you have to work around this by introducing an explicit resource for each apple, or a resource for each act of taking an apple, even though the latter is an abstract concept that does not represent a tangible object. If you try to implement the hypothetical addition procedure example given earlier, you run into similar problems. Real-world application logic is full of atomic operations and state transitions where the client simply cannot be trusted to determine the resulting state — whether due to possible race conditions, or business or even legal constraints — and this is where, unfortunately, REST's create/read/update/delete mantra falls flat.
There is another limitation common to both REST and SOAP. We celebrated the fact that single-page applications mean no longer having to update the server every time the client is modified. However, since the exact set of fields returned by the server is controlled by the server itself, when we need to display additional data we face a choice: either modify the server to send more fields, or issue an additional request to the server. A server returning more fields might mean that in the most common cases we are sending data that is not immediately useful to the client, wasting network bandwidth. This is called over-fetching. Forcing the client to establish an additional connection to the server in the rare cases where more data is needed means longer waiting times for the end user, since each connection is a cost we pay in network latency (the time it takes for data to reach the server and back). This is called under-fetching.

GraphQL
At last, we are ready to understand what GraphQL really is. In short, it is a programming language designed specifically to solve the problems of a modern web developer. It is also a set of API specifications that describe how to speak GraphQL over HTTP, the protocol used by web applications.
Although GraphQL is often compared to REST, in reality it is much closer to SOAP. It is an RPC mechanism that offers a collection of named operations (SOAP calls them procedures, whereas GraphQL has queries, mutations, and subscriptions).
Unlike SOAP, it uses a simple data format to represent objects. For this reason, it is very easy to handle in JavaScript code.
Unlike REST, it revolves around named operations rather than resources. This makes it easier to implement scenarios that do not correspond to tangible objects, or that operate on multiple objects simultaneously.
Unlike both SOAP and REST, it requires the client to specify the exact set of fields (including associated objects) it expects in return. This addresses the under-fetching and over-fetching problem while maintaining backward compatibility.
Unlike REST, GraphQL comes with an introspection interface, meaning API endpoints are self-documenting. This was a problem that SOAP ultimately addressed by distributing WSDL (Web Services Description Language) files, while REST clumsily attempts to solve the same problem by generating documentation pages that are often neither useful for human readers nor machine-friendly. The introspection mechanism interface has given life to a rich tooling ecosystem, including automated means of detecting whether client code references parts of the API the server considers deprecated (before their actual removal).
Since GraphQL separates its protocol specification from its transport specifications, it is possible for an application to use the same GraphQL engine both to resolve queries sent by web clients and to execute queries internally within the application — thus becoming the single data access mechanism for all business logic.
Given all its technological advances and the fact that the standard is now governed by its own GraphQL Foundation, operating under the Linux Foundation, do not let anyone convince you that GraphQL is nothing more than a passing trend, or just hype peddled by Facebook engineers who do not understand REST.
Freely translated from English: article saleor
Have a similar project?
Let's talk it over in 15 minutes. No sales pitch, just a technical chat.
