OpenSense Labs: Why Is GraphQL an Important Player in Decoupled Drupal?

Why Is GraphQL an Important Player in Decoupled Drupal?
Gurpreet Kaur
Fri, 11/20/2020 – 11:19

Drupal is a renowned name when it comes to website development. The kind of features and control it allows you to have on your content is quite impressive. The traditional Drupal architecture has repeatedly proven to be valuable and now it is the time for Decoupled Drupal architecture to do the same, which it is on the path of doing. A major reason for the increasing popularity and adoption of the decoupled Drupal is the freedom to make the front-end using the technologies you like.

Since the Decoupled Drupal architecture separates the presentation layer from the backend content, an API becomes the thread that holds the two together to work in sync. So, it is important to choose the right one for your project. While REST API and JSON: API are quite sought after, GraphQL has also emerged as a front runner. So, let us find out what exactly GraphQL is, what it can do and how it plays in the Decoupled Drupal architecture’s picture.

Decoding GraphQL 

The GraphQL logo along with the words GraphQL is written in its signature pink across a white background.
GraphQL, a query language, came into being about eight years ago, however, its popularity came through in 2016, when it was made open-source. Its founder, Facebook, created a unique API because they needed a program to fetch data from the entirety of its content repository. It is a system that is easy to learn and equally easy to implement, regardless of the massive proportions of data you may have or the massive number of sources you may want to go through. 

When I said that GraphQL is a query language, I meant just that. It is a language that will answer all your queries for data using its schema, which can easily be deployed using GraphiQL, an Integrated Development Environment. GraphQL, being a language specific for APIs, is equipped to manipulate data as well with the help of a versatile syntax. The GraphQL syntax was created in a way that it is able to outline the requirements and interactions of data to your particular needs. The shining glory of GraphQL is that you only get what you have asked for, nothing more, nothing less. This means that the application will only work towards retrieving data that is of the essence in the request. The data might have to be loaded from varying sources, but it will still be accurate and precise, succinct to the T and exactly what you sought.

With decoupling becoming a need now more than ever and content and presentation layers segregating from each other, GraphQL becomes the answer for all data queries, essentially becoming the answer for data retrieval for your API and your web application. A query language and a runtime to fulfil every query within your existing data, GraphQL is powered to paint a complete and totally understandable description of your data using the API. Its robust developer tools have proven to make APIs faster, more flexible and extremely friendly to our developer friends. Therefore, achieving decoupling becomes extremely easy as GraphQL provides typed, implementation agnostic contracts amongst systems. 

GraphQL vs JSON:API vs REST API

The power and assistance of APIs have become all the more conspicuous in the decoupled world. With three prominent names taking the lead here, it becomes somewhat tricky to get to the right API conclusion. GraphQL, JSON:API and REST API, all three have their own virtues making them great at whatever they intend to do. However, it becomes almost impossible to talk about one and ignore the other two. My writing would not have been complete without a comparison of the three.

If you look at the core functionality of these three APIs, you will realise that GraphQL and JSON: API are much more similar to each other than REST API, which is a whole other ball game compared to them. Let us look at them.

Parameters GraphQL JSON: API REST API
How much data is  retrieved?  Does not over-fetch data  Does not over-fetch data  Inundates the user with unnecessary proportions data 
How is the API explored? Has best API exploration due to GraphiQL Uses a browser to explore the API  Relatively does not perform well and the navigable links are rarely available
How is the schema documentation? Perfect auto-generated documentation and reliable schema Depends on OpenAPI standard and JSON:API specification only defines generic schema Depends on OpenAPI standard
How do the write operations work? Write operations are tricky Write operations come with complete solutions Writes can become tedious with multiple implementations
How streamlined it can be during installation and configuration? Provides numerous non-implementation specific developer tools but is low on scalability and security Provides numerous non-implementation specific developer tools and is high on scalability and security Provides numerous tools, but they require specific implementations and come with good scalability and high security

GraphQL

With GraphQL and its distinct fields of query, the developer is asked to specify each and every desired resource in these fields. You might be wondering why? The answer lies in its exactness. It is because of these explicitly mentioned desires that GraphQL never over-fetches data.

Coming to API exploration, GraphQL takes the cake for being the simplest and most conclusive. The fact that a GraphQL query comes with suggestions that can be auto-completed justifies my earlier claim. Moreover, the results are shown alongside the query resulting in smooth feedback. Its in-house IDE, GraphiQL, also helps in generating iterations of the queries, aiding the developers even more. 

If you told me that GraphQL specifications are more equipped at handling reads than writes, I would not object to you. Its mutations require you to create a new custom code every time. You can probably tell how much of a hassle it can be. Regardless, GraphQL can easily support bulk write operations that have already been implemented.

In terms of scalability, GraphQL requires additional tools to capitalise on its full potential and there are certainly numerous developer tools made available, and all of them are not implementation-specific.

JSON: API 

The problem of over-fetching is not witnessed with JSON:API as well. Its sparse fieldsets produce an output similar to GraphQL. However, unlike GraphQL’s uncacheable requests, JSON: API can omit the sparse fieldsets when they become too long and hence, can cache even the longest requests. 

With JSON: API, the explorations are simple as well; as simple as browsing within a web browser, which is basically what the API acts like here. From scouring through different resources to different fields and debugging, you can do all of that with your browser. Can data retrieval be simpler?

In terms of writings, JSON: API is probably the best out of the bunch. It offers a wholesome solution for handling writes by using POST and PATCH requests. Even though bulk support is not available at the moment, it is in the works and would soon be in use.

JSON: API is again similar to GraphQL as it also provides various developer tools that are not implementation-specific. The fact that its infrastructure resembles that of a website, requiring Varnish and CDN, makes it different from the former. 

REST API 

REST API has probably the most over-fetching system going on. Not only does it mandate multiple requests for one piece of content, it would also give you responses that are often even beyond the threshold of verbose. And the data that you end up with is so much more that you asked and needed. 

Again, REST API is completely different from the other two in terms of data exploration. And sadly, this isn’t a good kind of different. REST API is highly dependent on an OpenAPI standard, and if you are not adhering to that, things would seem a tad bleak for you. You will not be able to trust it for an auto-generated documentation or a validatable and programmable schema. The navigation through high volumes of data seeking interactivity is not too impressive either. 

Writing data in REST API is quite easy, almost as easy as reading it. Using POST and PATCH requests, every implementation is unique. Bulk support is not on the table. 

REST API’s infrastructural needs also resemble that of an ordinary website encompassing Varnish or CDN. However, its additional tools, although many, mandate customisation before implementation.

The GraphQL and Decoupled Drupal Dynamic 

GraphQL is a language that is undergoing developments as I am writing and you will be reading, but that does not mean that it is unstable. Moreover, GraphQL is being capitalised by several Drupal websites. The exactness in responses along with the always available introspection layer makes GraphQL truly worth it.

Let us now understand how it is the perfect answer to Decoupled Drupal by asking all the right questions or shall I say queries?

How does Drupal fully capitalise GraphQL?

Drupal can be rigid, it is a fact all of us know. Apart from this, Drupal can also seem to be too much with everything it has to offer. What GraphQL does is, it gives you the ability and the power to create and expose a custom schema that would eventually become the only roadway to all the data; information, operations and interactions, whatever happens within the system. And then, Drupal does not seem to be too rigid. 

You get a GraphQL module in Drupal  which is designed around webonyx or graphql-php. What this means is that the module is basically as jam-packed with features as the actual language is with all the GraphQL specifications.

  • The module can be used as the basis for creating your very own schema by generating a custom code;
  • The module can also be used to extend the already existing schema with the use of the plugin architecture, wherein the plugin would act as the sub-module.
  • To aid development even more, GraphiQL is also included at /graphql/explorer, which acts as a user interface for you.
  • Lastly, there are built-in debugging tools that are competent to issue queries and analyse their responses and that too in real time.

GraphQL is a powerful tool and Drupal has ensured that all its community can easily tap into its power.

The GraphQL Twig module is the next advancement in Drupal. It was and generally is thought that GraphQL queries can only be sent over HTTP, but that isn’t true. It can be, but there are other ways as well and this module personifies that. You can segregate the Twig templates from the internal structures of Drupal, so that maintenance and reuse is easier without any involvement of HTTP.

Should we use GraphQL or JSON:API or REST in Drupal?

Before getting into why GraphQL, we have to understand why not REST and what are its limitations. First of all, REST UI is absolutely important to set up the REST module in Drupal. Not to forget, it can be pretty arduous to configure it. In addition, the primary problem with REST is that it over fetches information, bombarding you with data you do not even need and certainly did not ask for. You might have just needed the title of an article, but the author’s user id is also included in the response list. This leads to a cycle of follow-up queries and you end up with the article’s title, link, its author’s name, his information and the entire content of the said article. Over-fetching is putting it lightly.

Because GraphQL uses the APIs in a more simplistic way, it becomes better than REST endpoints. The former does not expose single resources with fixed data structures and links between them, rather it provides you the opportunity to request any selection of data that you may need. You can easily query multiple resources on the server side simultaneously, consequently combining the different pieces of data in one single query. Hence, your work as a front-end developer becomes as easy as pie. You could still go for REST, if you wanted, it does have its own set of merits

Now coming to choosing between JSON: API and GraphQL, this is a more difficult choice to make. These two perform at a level parallel to each other. For instance, installing the JSON: API module is a piece of cake with absolutely no configuration required. As for GraphQL, the installation is easy as well, but there is a need for some configuration. Do you see why I said the choice was difficult?

Where decoupling is concerned, JSON: API and GraphQL are much better than REST. Server-side configuration is not required by the clients to perform content queries. While JSON: API has the default setting of altering every client-generated query, GraphQL mandates the permissions to be held by the consumer so that he can forego any access restrictions. There is no right or wrong method here, both have the right filtering tools for decoupling and both are security for your content.

When is the GraphQL module the most suitable?

Only fetching the data that is asked for should be the tagline of GraphQL and that is why in scenarios where you need data retrieval, it becomes quite handy.

  • Decoupled Drupal applications, with Drupal as the content repository and a React, Angular or Ember powered front-end.
  • Mobile applications, wherein data storage is the need of the hour.
  • Internet of Things data storage.
  • If you want to retrieve the JSON data from Drupal.
  • And also if you plan to use the Twig Templates in Drupal themes.

The GraphQL module would be perfect in all of these instances.

Why do GraphQL and Drupal fit so well?

GraphQL is considered to be an excellent fit for Decoupled Drupal websites, especially if they comprise entities as fields for stored data and these fields have relationships with other entities. GraphQL helps you curate queries for just the fields you need from the Article. This kind of flexibility makes it easy to restructure an object you wanted back, helping you to change the display as well. You can write queries, add or remove fields from the results and you can do all of this without writing a code on the backend.  The GraphQL module’s ability to expose every entity including pages, users and customer data makes all of this seem quite simple. So, it would be suffice to say that the decoupling experience would not be the same without GraphQL.

Has GraphQL impacted the conventional server-client relationship?

Traditionally, the server was the dominant in the server-client relationship, however, now the client holds more power and GraphQL has made certain of this. With it, the client need not follow everything the server imposes, it can simply enunciate its needs on a per-request basis. After the server would show the data possibilities it is equipped to fulfil, it would be extremely easy for the client to define its needs with the catalogued possibilities at the forefront. The shape of the values GraphQL API inserts and returns is every bit the same.

On top of these, GraphQL taps into the deeply nested relational data structures, which are suitable for graph models. The abilities of GraphQL schema and query validation ensures that it can prevent distributed denial-of-service attacks, thereby preventing attempts at overloading queries. The benefits of GraphQL in Drupal are indeed far and many.

What Will the Future Look Like?

GraphQL is not a part of Drupal Core, being an advanced tool that is a little more complex to use. The future is not showing any signs of it becoming one either. However, there are other aspects to look forward to. GraphQL v4 for Drupal is one of the most awaited releases of the GraphQL module. It would bring along numerous improvements for the module that seems to be perpetually evolving. GraphQL schema will be in total control of Drupal developers, since schema customisation was the holy grail of this module, things are looking up and the future brighter. GraphQL and Drupal have a long way to go.
 

blog banner
There are two computer screens, denoting the association of Drupal and GraphQL.

blog image
A structure of a building can be seen.

Blog Type
Is it a good read ?
On