GraphQL is the new frontier in Application Programming Interfaces (APIs) - a query language for your API and a set of server-side runtimes (implemented in various backend languages) for executing queries. Further, it isn't tied to any specific database or storage engine; instead backed by your existing code and data.

If you are a Javascript developer then there are better chances that you have heard of it. But you are not sure about it. To help you out, I have written this blog post so that you can easily figure out what exactly is GraphQL and how to make most of it. When you will complete this GraphQL blog cum tutorial, you will be able to answer:

  • What is GraphQL

  • Core ideas of GraphQL & limitations of RESTful APIs

  • How GraphQL resolves the limitations of RESTful APIs

  • How GraphQL can be used in Drupal

Let’s get started.

So what is GraphQL?

As I mentioned earlier, GraphQL is a query language for fetching application data in a uniform way. Developed by Facebook in 2012, GraphQL was rolled out in 2015. And for few years, the social media giant used it for internal purpose.

Cutting straight to the chase. GraphQL is a methodology that directly competes with REST (Representational state transfer) APIs, much like REST competed with SOAP at first.

Core Ideas of GraphQL

  1. Client Requests and Server payloads have the same structure.

  2. The server contains the schema.

  3. The client dictates what it wants from the server to provide.

Limitation of RESTful API’s

  1. Multiple Endpoints -- Endpoints are specific to individual views. With a REST approach, you can create multiple endpoints and use HTTP verbs to distinguish read actions (GET) and write actions (POST, PUT, DELETE).

  2. Overfetching -- Response contains more data, mostly unused. For instance, if you hit this URL https://swapi.co/api/people/1/ the response consists of large amount of data like eye-color, gender, links to films. etc.

Sample Api Response

 3. Many Round Trips  -- In the previous URL response, you can see films contain a list of URLs. So in order to get the detail of films you need to hit these URLs resulting in multiple round trips to the server.

How GraphQL Resolves The Limitations of RESTful APIs

  1. Single Endpoint -- Single Endpoint can resolve GraphQL queries and send a single, unified response. GraphQL does not use HTTP verbs to determine the request type.

  2. Tailored Response -- Response is catered to the client demand. With GraphQL you explicitly request just the information you need, you don’t “opt out” from the full response default, but it’s mandatory to pick the fields you want. This helps by saving resources on the server since the payload to transfer is smaller.

  3. Fewer Round Trips -- Returns a single response flexible to accommodate many relationships.

GraphQL in Drupal:

Drupal provides a module named graphql that lets you craft and expose a GraphQL schema for Drupal 8. It is built around a PHP port of GraphQL to support the full official GraphQL specification with all its features.

You can use this module as a foundation for building your own schema through custom code or you can use and extend the generated schema using the plugin architecture. Here the provided plugin implementations will form the sub-module.

There are some other modules based on it like:

  1. GraphQL Mutation: - Core module with common fields and types for enabling mutations.

  2. GraphQL JSON: - Extract data from various JSON sources.

  3. GraphQL Views: - It provides support for views

The above mutation & JSON modules are in dev version and the views have an alpha release. You can try out these to know more.

Drupal provides an in-browser IDE interface to execute GraphQL queries. You can find that in “graphql/explorer”.

GraphQl Explorer in Drupal 8

Let’s try our hands on some of the GraphQl Queries & Mutations.

  1. Fields: Write a simple nodeQuery which will return entitylabel & entityid.

 

The response of the above query will be similar to this.

As you can see the response is similar to the actual query. This is essential to GraphQL because you always get back what you expect, and the server knows exactly what fields the client is asking for.

2. Query with arguments

In the above query, we are getting the title of a node by passing an argument which is the node id. Response from above query will be

3. Query with Filters

The above query filters nodes by publish status resulting in the below response.

4. Aliases:

Aliases let you rename the result of a field to anything you want. You can't directly query for the same field with different arguments. If you do a query like this you will get an error:

The error will be like this: "Fields \"nodeById\" conflict because they have differing arguments." This is where aliases come to rescue. Using it we can give an alias to the two queries as shown below.

5. Fragments: GraphQL includes reusable units called fragments. Fragments let you construct sets of fields, and then include them in queries where you need to. In the below example, you can see I have created a fragment nodeFields.

The above query will generate a response like this

6. Variables:

Sometimes we need to pass dynamic values to query. We can pass dynamic values using variables in GraphQL.

When you start working with variables, we need to do three things:

  1. Replace the static value in the query with $variableName

  2. Declare $variableName as one of the variables accepted by the query

  3. Pass variableName: value in the separate, transport-specific (usually JSON) variables dictionary

7. Mutation

Most discussions of GraphQL focus on data fetching, but any complete data platform needs a way to modify server-side data as well. The module GraphQL Mutation is needed to perform POST operations. https://www.drupal.org/project/graphql_mutation. It adds GraphQL mutations for all content entities.

So now you are familiar with some of the above-mentioned operations in GraphQL. You can learn more about these in http://graphql.org/learn/. GraphQL can be used to build decoupled Drupal. Here in Github, you can see an example. https://github.com/fubhy/drupal-decoupled-app.

Please comment below if you have any questions or feedback.

Below given is a short presenation on GraphQL.

 

comments powered by Disqus