GraphQL was designed for more powerful and user-friendly client-server interaction. This complex solution is a query language and execution engine. GraphQL is developing quickly and is available as a web service in Drupal 8, 9, and 10. Drupal websites often use GraphQL. This solution is particularly robust as a web service and focuses on an easily accessible level of introspection and customization. Let's take a closer look at the features and potential of GraphQL in Drupal development.
What is GraphQL in Drupal?
GraphQL in Drupal is an adaptive standard for APIs. This solution is specifically created for the environment running these queries. GraphQL allows you to get complete and reasonable information about the state of your API. The solution allows the client to get the exact response he needs from the API, so the exact request should always be given.
Why use GraphQL?
There are many reasons why you should use GraphQL:
- GraphQL makes aggregating data from multiple sources or APIs easier and then resolving the data to the client in a single API call.
- The client can ask for only the data he needs.
- Many mobile devices such as smartphones, smartwatches, and IoT gadgets face a challenge with limited bandwidth, which restricts their ability to process large volumes of data.
- GraphQL uses a single endpoint so that clients can access a few different resources. At the same time, the resources are displayed according to views that differ from those in your application.
GraphQL advantages and disadvantages
You should use GraphQL for Drupal because of its numerous benefits:
- GraphQL gives the exact answer to the client's request. The service always produces a predictable result. GraphQL applications are also stable because they work based on received data, not server data.
- Accelerated interface development. You don't have to wait for new service endpoints to provision an application. The client can make the data fetch into the desired shape, improving code maintenance.
- Using existing data. GraphQL solution can be used with any existing framework like database or REST, or SOAP. Thus, the client can ask for all the necessary data in one request and immediately receive an accurate answer.
- Fewer cycles and bytes. The GraphQL module lets you get all the necessary data in one query. This lets you significantly speed up applications
Despite the GraphQL flexibility and all advantages listed above, there are some disadvantages that we should mention. GraphQL is not the best choice if your team is small and you have a tight budget. But there are a few more important cons that you should know about:
- There is not enough documentation, and it is not always up-to-date. If you want to find learning resources, there aren't many. On www.drupal.org/docs/graphql, you will also see slightly outdated information. Therefore, GraphQL should only be used by those with experience. Otherwise, it will be challenging for you.
- You will have to share everything with your front end. GraphQL will not suit you if you do not have enough time and knowledge. Be prepared to work with navigation, including all menu sections, as well as links, all content pieces, and other fields available in your application.
- If you plan to use GraphQL, you will have to start from the very beginning, building everything from scratch. GraphQL works on the same principle as JSON API and REST. Before versions 3 and 4, the module had access to all application resources at the installation stage. Therefore, it was enough just to install it to gain control over all entities. But now everything has changed. To use GraphQL, you will have to create all the schemas for each resource and entity independently.
Installing GraphQL for Drupal
The Drupal GraphQL module supports all GraphQL specifications and can be used to create and provide GraphQL schemas.
- You can visit the drupal.org site to find official instructions on how to install the Drupal GraphQL module.
- Use the composer command: composer require drupal/graphql:^3.0.'
- After running the command, you will get GraphQL and GraphQL Core modules.
Both modules must be enabled. You can enable them using the drush command:
drush en graphql
drush en graphql_core
Short guidance on integrating GraphQL into the Drupal project
The first thing about Drupal is to understand its components. GraphQL processing includes 3 fundamental parts that you cannot do without:
- Graphs. The client must follow a clear folder structure and file extensions to build a valid query. All GraphQL files will be contained in the app/modules/contrib/graphql/examples/graphql_example/graphql folder. Using special characters like ! and  is needed to specify the correct order of arrays and fields.
- Data producers are used in GraphQL to properly map and resolve data in a clear sequence for the application to work properly.
- Schemes. They are required to obtain data permissions and be able to map them to the corresponding field names according to the GraphQL files.
Queries with Drupal GraphQL
GraphiQL is a powerful solution with an interactive UI with functionalities like auto-completion. Using this tool, you can run queries and get outputs. Go to “/graphql/explorer” for the interface to start navigation.
You can write a query on the UI's left side panel. The results in JSON format you will see on the right side. Clicking on Docs at the top right corner will get you the documentation of the available queries. The Query Variable section on the bottom left panel can be used to pass query variables.
The most popular queries in GraphQL are the following:
- Filters with conjunction
Conjunctions can be of two values:
If you need to write more complex queries, you can use Groups.
Is GraphQL better than REST API and JSON API?
Both REST and GraphQL APIs are ways to call functions over the network. If you're familiar with building a REST API, implementing the GraphQL API won't be much different. However, GraphQL has a big advantage. This is the ability to call several related functions within a single request.
Summarizing, we can draw the following conclusions about the similarities and differences between these solutions:
- Endpoints in REST and fields in GraphQL end up calling functions on the server.
- Both REST and GraphQL typically rely on frameworks and libraries for the chore of networking.
- In REST, each request usually calls exactly one route handler function. In GraphQL, a single query can call many resolver functions to build a complex response with many nested resources.
- In REST, you build the response from yourself. In GraphQL, the form of the reaction is defined by the GraphQL executing library to match the form of the request.
Some of the differences speak in favor of GraphQL. It's great to implement your API as a set of small resolver functions and then make complex requests that fetch many resources at once predictably.
On the other hand, GraphQL does not yet have as many integration tools and solutions as there are for REST. For example, you can't cache GraphQL API results with HTTP caching as easily as you can with REST API results. However, the community is working hard to improve the tools and infrastructure.
Talking about JSON: API, we need to mention its advantages. Its web standards-based approach, ability to handle reads and writes out of the box, security model, and ease of operation make it a good choice for Drupal Core.
Many developers think it's better to choose JSON: API or REST as modules offer more use cases. But there are many situations listed above where GraphQL is a great solution. Drupal provides so many options for its users that it is always possible to choose the best variant according to your situation.
Best practices for query optimization, error handling, and versioning in GraphQL-powered Drupal applications
When creating queries and mutations, follow these best practices to get the most out of GraphQL:
- All operations must have names. However, some queries can retrieve the same data—for example, an anonymous request and a GetBooks request.
- The exact name of the GraphQL operations to execute is necessary to avoid errors in your application. Otherwise, multiple operations may be combined in a single request, causing problems. Note that there can only be one anonymous operation.
- Fragments in GraphQL are special sets of fields required to perform several operations. Fragments can be used to encapsulate related field groups.
- Fragments should be logical and clear. Don't use too many pieces because the readability of your queries may deteriorate.
- Avoid creating fragments when the same fields are used for different queries. Fragments are only suitable for areas that are logically and semantically related.
- You should not request user data and global data at the same time.
- Please note that there are fields that give the same data regardless of the user who requested them.
- To get the correct metrics reports, select a name for your app and set the appropriate version.
GraphQL is a great choice for querying databases with many records. It is highly flexible, allowing you to eliminate oversampling, extracting only the data you need in specific formats, thereby improving application performance. In addition, GraphQL is well suited for those situations where you need to combine data from multiple resources.
It can also be used when you don't quite understand how the client uses the API. In GraphQL, there is no need to define a strict contract in advance. Instead, you can incrementally build the API based on customer feedback. If you want to stay at the forefront of modern web development, try GraphQL to unlock the full potential of Drupal.