Blogs

EMAIL: info@example.com

Specbee: GraphQL with Drupal 8 : The All-You-Need-To-Know Guide (with examples!)

GraphQL with Drupal 8 : The All-You-Need-To-Know Guide (with examples!)
Pradosh
17 Dec, 2019

GraphQL talks to Drupal in HTTP and the outputs are more structured than ever before!

Today, great customer experiences begin with great content. Content that is made available everywhere. With Drupal 8’s API-first initiative, the content that is managed by Drupal can be readily used by other systems over HTTP. REST (Representational State Transfer) provides a design standard for APIs. However, with client applications getting more complex and challenging, developers need a more modern and effective solution.

GraphQL was born out of the demand for a more flexible and powerful client-server interaction. It is a sophisticated query language and an execution machine. In 2012 Facebook created the specification for it, which describes its capabilities and the requirements of data models for headless applications. 

What is GraphQL? 

GraphQL is an adaptive standard for APIs and provides a runtime to fulfill those queries. GraphQL gives a complete and reasonable details of the information in your API. It’s developed with an ideology of “Ask for what you need and get exactly that”. It empowers the client to fetch for the exact response they need from the API, nothing more – nothing less. 

GraphQL Advantages

Few of the many advantages of using GraphQL for Drupal –

  1. Faster frontend development

    Emphasize quickly on applications without waiting for new backend endpoints. Improve data fetching and code maintenance by getting the data in the shape you need.
     

  2. Ask for what you need and get exactly that

    It provides the exact response the client asked for. It always returns predictable result. Applications using GraphQL are also stable because the application controls the data it gets, not the server.
     

  3. Use your existing data

    GraphQL can be used with any existing infrastructure e.g. REST, SOAP or existing database, or anything else. It allows you to query all the data in a single request and provides you a cleaned predictable response.
     

  4. Fewer bytes and roundtrips

    Using GraphQL all the required data can be fetched using single query. It’s makes the
    application faster.

drupal-graphql
                                 GraphQL with Drupal 8

REST vs JSON:API vs GraphQL

If we compare these three according to request efficiency, JSON:API and GraphQL are excellent. Because in a single request JSON:API and GraphQl can serve all the required responses. In case of JSON:API, sometimes we have to tailor the response but when it comes to GraphQL, it only serves what we need. REST is slower as compared to these, because multiple requests are needed to serve the common needs. 

In terms of operational simplicity and implementation, REST is the easiest, it has been there for quite a while now. JSON:API also works out of the box with CDN and reverse proxies. For GraphQL extra infrastructure is needed and client libraries are necessary to implement it. 

It’s easier to use web cache in REST and JSON:API as compared to GraphQL. In GraphQL, there’s only one endpoint (most of the time an HTTP POST endpoint) where all the queries are sent. Since each query can be different, it is harder to use this type of caching.

The Drupal GraphQL specification supports bulk/batch operations automatically for the mutations you’ve already implemented, whereas the JSON:API specification does not. The ability to perform batch write operations can be important.

Installing GraphQL for Drupal 8

The Drupal GraphQL module supports all the GraphQL specifications and can be used to build and expose GraphQL schemas. The latest alpha release of the Drupal 8 module in the version 8.x-4 offers a capability for Drupal modules to extend the schema with a plugin.

Here is where you can install Drupal GraphQL module from – https://www.drupal.org/project/graphql
You can install using composer command.

composer require 'drupal/graphql:^3.0'

It will provide you two modules GraphQL Core and GraphQL. You need to enable both the modules. You can enable it using drush e.g.

drush en graphql
drush en graphql_core

Queries with Drupal GraphQL

Drupal GraphQL module provides a tool called GraphiQL. It’s a powerful tool and has an interactive UI with functionalities like auto completion. Using this tool, you can run queries and get outputs. Navigate to – “/graphql/explorer” for the interface.

You will get a UI that looks like this –

GraphQL-UI
           
           GraphiQL UI

On the left side panel of this UI you can write a query and on the right side, you will see the results as an output in JSON format. Clicking on Docs at top right corner, will get you the documentation of the available queries. Query Variable section on the bottom left panel can be used to pass query variables.

Examples

1.Querying Nodes

Quering-nodes-graphql
            
            Drupal GraphQL – Querying Nodes

2. Querying Taxonomies

Drupal GraphQL - Querying Taxonomies
      
           Drupal GraphQL – Querying Taxonomies

3. Querying Routes

Drupal GraphQL - Querying Routes
          Drupal GraphQL – Querying Routes

4. Query Fragments

Drupal GraphQL - Query Fragments
          Drupal GraphQL – Query Fragments

5.Filters

Drupal GraphQL - Filters
            Drupal GraphQL – Filters

6. Filters with conjunction

Drupal GraphQL - Filters with Conjunction
         Drupal GraphQL – Filters with Conjunction

Other available operators are: 

  • EQUAL
  • NOT_EQUAL
  • SMALLER_THAN
  • SMALLER_THAN_OR_EQUAL
  • GREATER_THAN
  • GREATER_THAN_OR_EQUAL
  • IN
  • NOT_IN
  • LIKE
  • NOT_LIKE
  • BETWEEN
  • NOT_BETWEEN
  • IS_NULL
  • IS_NOT_NULL

Conjunctions can have two values

  • AND
  • OR

You can also use Groups to write more complex queries.

7.GraphQL variables

Drupal GraphQL - Variables
           Drupal GraphQL – Variables

Mutations

In GraphQL, a mutation is the terminology used whenever you want to add, modify, or delete data stored on the server. In this case, Drupal. Unfortunately, the module does not include a way to perform common mutations out of the box due to some technical requirements of GraphQL.
Example code for creating, deleting, updating, and file uploads, can be found here: https://github.com/drupal-graphql/graphql-examples

Example mutation:

Drupal GraphQL - Mutation example
           Drupal GraphQL – Mutation example

Drupal GraphQL with Twig

Using Drupal GraphQL with Twig can significantly improve the performance of your website. Here’s how – When you inject data into the Twig template, you can fetch all the required data using a single API call. Moreover, because the client controls the data they get and not the server, it makes the process even faster.

To use Drupal GraphQL with Twig we need the GraphQL Twig module. To download and enable it, use the following commands:

composer require 'drupal/graphql_twig:^1.0'
drush en graphql_twig

And then you can use GraphQL query in your website e.g.

{#graphql
query {
  admin:userById(id: "1") {
    uid
    name
  }
  user:currentUserContext {
    uid
  }
}
#}

You will get the response data in the GraphQL variable.

Shefali ShettyApr 05, 2017