Published on

Introduction to GraphQL

Have you heard of GraphQL lately? Ever wonder what it is? If so, keep reading to find out!

A GraphQL meme🙂

Figure 1: A GraphQL meme🙂

In this blog post we will give an overview of what GraphQL is, why it is useful, and how to use it. So without further delay, let's begin!

GraphQL Overview

GraphQL can be though of as an intermediary layer between the frontend and the backend of traditional client-server applications. It is mainly a query language. A query language is a specialized programming language for searching and changing the contents of a database. It is also considered a runtime environment, that is, software that provides the application to be run a more convenient environment for execution.

Primarily GraphQL executes queries using a custom type system that defines the application data. Therefore, it is important to note that GraphQL is not linked or associated with any specific database technology or storage engine. Instead, it is supported only by the existing code in the user's frontend and backend applications and the data that they contain.

GraphQL was developed as an alternative to the traditional REST API(click here is learn more about them from SmashingMagazine.com) because REST APIs often get convoluted, tedious and cumbersome when additional features and complexity is introduced. For example, if you used a REST API to fetch data, it will always return a complete dataset. So a request calling for two objects would require two REST API requests. This causes inefficiencies when dealing with requests on a large scale, which is all too common these days.

Also the inefficiency known as over fetching, whereby a request to a REST API returns the desired properties of an object along with redundant properties, is all too prevalent when using REST APIs. GraphQL on the other hand is much flexible in that it allows the developer to custom tailor requests so that only the object properties desired by a given request(also known as queries in GraphQL lingo)are returned when the request is executed. This feature extends to entities of different types, so that objects of multiple entity types can be returned in the same request as long as a matching query is defined by the developer. Here is an example GraphQL query response showing this feature in action:

{
 airplane(id: 3) {
     id
     model
     size
     passengers [
      {
         id
         name
         email
         carry_on_baggage {
             id
             weight
             baggage_brand
             baggage_color
         }
      }
     ]
 }
}

GraphQL Operations

There are three main operations that are primarily used in GraphQL and they are:

Queries

This operation is used to read and fetch data from an API. GraphQL queries differ from traditional REST API requests because they allow for more customization in terms of the fields and properties that should be returned for a given query. In other words, they prevent data over fetching. Here is an simple example of a GraphQL query:

  query {
        tweets {
            title
            body
            author {
                firstName
                lastName
            }
            published
        }
    }

Also note that queries are implemented via HTTP POST requests that are sent from the client, going through GraphQL, and finally to the backend or database implementation.

Mutations

Mutations are used to write or post data to an API. They are analogous to POST and PUT requests in terms of traditional REST API calls. Where GraphQL mutations have the upper hand over REST POST/PUT requests is when dealing with complex and nested relationships in the domain layer. This is because updating values through mutations is much easier than having to create nested REST endpoints, as you would have to if choosing to use the traditional REST API architecture. It is also worth noting that mutations allow for values to be returned after the data updating has taken place, which effectively eliminates the need for subsequent queries to be run.
Here is a simple example of a GraphQL mutation:

 mutation createTweet(
        $title: String!
        $body: String!
        $published: Boolean!
        $authorId: ID!
    ){
        createTweet(
            data: {
                title: $title
                body: $body
                published: $published
                author: $authorId
            }
        ) {
            title
            body
            author {
                firstName
                lastName
            }
            published
        }

    }

The above mutation is basically creating a tweet object that containing the fields listed above. After the tweet object is created, the title, body, author's firstName and lastName are returned as a response to this mutation.

Finally, keep in mind that GraphQL mutations are implemented as HTTP POST requests so there is no magic under the hood of GraphQL😅

Subscriptions

Subscriptions are similar to queries with the additional benefit of being long-lasting operations. This means that they can uphold an active connection to the GraphQL server which allows the server to push real-time updates to the subscription which is then passed to the client as well.

Where subscriptions excel is instances where the server needs to notify the client of data changes that are happening at mostly instantaneous speeds. Accordingly, some practical uses of GraphQL subscriptions may include services you are already familiar with such as showing the amount of likes in Facebook Live sessions and showing the amount of comments in Instagram Live sessions.

  subscription {
        tweet {
            mutation
            data {
                title
                body
                author {
                    firstName
                    lastName
                }
                published
            }
        }
    }

The above code adds a subscription to the tweet channel and start listening to any events published in that channel.

Finally, it is worth noting that GraphQL subscriptions are implemented as WebSocket connections using the WebSocket API(more on WebSockets here)

GraphQL Schema Definition Language

So far we have been discussing only one of the two main concepts in GraphQL, that being the Query language. Now let's talk about the other concept: the Schema Definition language.

The schema definition language can be though of as a language used to define the schema and store it as a string while making sure to preserve it in human readable format. A schema defines a collection of data types on top of specifying the relationships that exist between those data types. Here is an example of a GraphQL schema:

type User {
    id: ID!
    firstName: String!
    lastName: String!
    email: String!
    age: Int
    tweets: [Tweet!]!
    comments: [Comment!]!
}

type Tweet {
    id: ID!
    title: String!
    body: String!
    published: Boolean!
    author: User!
    comments: [Comment!]!
}

type Comment {
    id: ID!
    text: String!
    author: User!
    tweet: Tweet!
}

Every field defined in the schema above consist of scalar and object data types, among other data types(learn more about data types at their official GraphQL documentation page).

Scalar data types are analogous to primitive types in traditional programming languages such as C and Java. In GraphQL these scalar types consists of the following:

  • Int: A signed 32-bit integer
  • String: A UTF-8 character sequence
  • Boolean: traditional boolean values, either true or false
  • Float: A signed double-precision floating-point value
  • ID: Unique identifier that is frequently used when getting or fetching object with this property being used as the identifier

Object types on the other hand, are types are defined in the GraphQL schema itself and contain their own collection of fields. Some of those fields might be scalar types and other might be other object types. Here is an example of an object type:

type Comment {
    id: ID!
    text: String!
    author: User!
    tweet: Tweet!
}

Now you might be wondering the purpose of including a "!" mark at the end of each field described in the object type above. This is to denote that those fields are non-nullable, meaning that they cannot contain null values. Another point worth clarifying is the [Comment!] syntax shown two examples above. These instances are known as list fields and they are used to indicate that a field can return a list containing items of a specific type.

Conclusion

Ok for the sake of keeping this an introductory blog post on GraphQL we will conclude it here. Hopefully you now have a better idea of what GraphQL is and why we use it.

Thanks for reading this blog post on an introduction to GraphQL!

If you have any questions or concerns please feel free to post a comment in this post and I will get back to you when I find the time.

If you found this article helpful please share it and make sure to follow me on Twitter and GitHub, connect with me on LinkedIn and subscribe to my YouTube channel.