Introduction: Overview of GraphQL

Sagar Barawade
Globant
Published in
9 min readJan 8, 2021

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. As an alternative to REST, GraphQL is quickly gaining popularity as a tool for building APIs. This article introduces to you, GraphQL concepts such as the GraphQL type system and schema and demonstrates how to build a GraphQL service that connects to a database using JavaScript. For better clarity and understanding, we have divided our entire journey of exploration of the GraphQL into 3 articles.

Article 1: Introduction: Overview of GraphQL
Here you will get the basic idea of what is GraphQL and why you need to give it a shot.

Article 2: GraphQL: The Query Language
Here, you will be able to understand in detail and practice the GraphQL querying mechanism on the GitHub interface known as GraphQLHub.

Article 3: Play it your way: POC on GraphQL
Now that you have got enough information about the query language, it's time to start building your own project. We’ll show you how to create a project with GraphQL in Javascript that connects with 2 databases, namely MySQL and MongoDB.

Existing data fetching system

First of all, let us go through the existing data fetching system which is based on RESTful Services. Below is a simple REST API based flow of request and response. This flow involves multiple API calls to fetch posts and their associated data & metadata.

Existing data fetching system based on RESTful Services
  • For fetching different sets of data we need to design multiple/different API endpoints whenever it would be required.
  • Sometimes we need only some specific fields but we still end-up fetching full response instead of those specific fields and there is unnecessary network overhead added, impacting lower bandwidth users.
  • In case if we want to have the flexibility of able to choose fields, we need to formulate a way of projecting fields that we want the API to return.
  • When we deal with multiple databases, managing relationships between them becomes challenging and when any of them is non-relational then it becomes a bit of a headache.

These are a few challenges we face with the current system residing at the server-side, now let's look at the challenges that we are facing as a developer at App side.

App data challenges

Data requirements vary across devices:
In today’s era, it is very common to have multiple clients of a product. All of these clients(WebUI, Android, iOS, Wearable OSes) may hit the same backend APIs. And all clients may not essentially be using all the fields returned in the response from the back-end. This results in over-fetching, network overhead, and slowing down of apps and in-turn giving a poor user experience.

Users want instant access to the Data:
In this fast-paced world, users have become very volatile. Let’s take an example of E-Commerce Apps like Amazon, Flipkart, etc. If a user is looking for buying a mobile phone and opens Amazon App, then types the search text and the moment the user enters the search and the App shows a spinner which makes the user wait until a matching product is found in the store. The user might have a frustrating experience of having to wait for it for a considerable amount of time. With this example, we can understand that even a second of delay could incur huge losses to the business, and with growing app complexities, it becomes a challenge to maintain the same user experience as before.

Building scalable data-driven apps without a deep understanding of distributed systems:
Today's applications are highly data-driven and achieving scalability at both the frontend and backend keeping the same user experience is the crucial thing, and with an unclear understanding of the distributed system, it becomes difficult to manage the changing requirements as time progresses.

But don’t worry, GraphQL can really solve this problem to some extent in a simpler way. Let's explore that further.

About GraphQL

The definition says that GraphQL is a query language for APIs & runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need, and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

  • GraphQL at its core is a language for querying databases from client-side applications.
  • On the other hand, backend GraphQL runtime parses the query and decides how to present the data to the client.
Evolution of GraphQL

Let’s look at the origin of GraphQL. Facebook conceptualized and developed GraphQL. They developed it initially as part of their optimization initiative and later on, they made it open source in 2015. From then onwards, it started evolving with respect to the business case scenarios and market needs. GraphQL quickly grabbed attention in the tech world and has been adopted by several notable companies, including Github, Yelp, Coursera, and Shopify, replacing existing REST APIs.

Type system
GraphQL has a type system that defines various data types that it uses.

  • Scalars (Single value)
  • Objects
  • Interfaces
  • Unions
  • Enumerations
  • Lists

Scalars
These data types help define schemas. With schemas and data types, GraphQL becomes a strongly typed language.

  • String
  • Float
  • Int
  • Boolean
  • ID
  • Custom scalars (Date etc)

We will discuss these Type System with Scalars in details with examples in the next article (Article 2)

GraphQL Architecture

GraphQL is a specification that describes the behavior of a GraphQL server. It is a set of guidelines on how requests and responses should be handled like supported protocols, the format of the data that can be accepted by the server, the format of the response returned by the server, etc. GraphQL can work with any database or data layer, allowing for a single GraphQL service to fetch data from multiple sources in a single request served by the composed API.

GraphQL Architecture

In the above architecture diagram, various clients with data requirements and specifications can connect to the GraphQL server and the server will respond back with the requested data as and when it is required from the relevant database. GraphQL can fetch data not only from SQL, No-SQL & In-memory DB but it also possesses the ability to connect to Microservices & Cloud databases. This ability makes GraphQL a database Neutral & friendly interface.

GraphQL’s Market Popularity

Below is the chart of GraphQL’s market popularity. As you can see in the chart, the developer's interest in GraphQL has grown substantially over time. We can observe from the chart that GraphQL is giving head to head competition to REST.

Google search results for Developer interests over time (Worldwide)

You can always get the updated chart here

GraphQL Operations

GraphQL supports all operations like Create, Read, Update and Delete, just like RESTful APIs but in a slightly different way. And related terminologies are very much easy to understand.

Let’s take an example of an E-commerce website that sells books. We’ll see how all the operations work in the scope of E-commerce actions.

1. Read Data: Queries
The first operation in GraphQL is to read the Data. In GraphQL, we call it Query & in REST it’s R i.e. Read, (GET operation)
Let’s take a scenario where you are searching for a book. The query will be like this:

Query {    
search(title: ”name”)
{
title
author
}
}

It will fetch all the books whose title matches the title provided. This is Read operation

2. Write Data: Mutations
The next operation in GraphQL is to add the data. In GraphQL, we call it Mutation. The rest of the operations in RESTful APIs such as Create, Update & Delete are called Mutations in GraphQL terminology. So likewise, POST/PUT/DELETE operations are nothing but Mutations.

Mutation {
create(title: ”book”)
{
id
}
}

The above code snippet will create a new record of a book with the title ‘book’ and return the `id` of the newly created record in the response. You have full flexibility to return a custom response as well.

3. Listen for Data: Subscriptions
The last operation is the Subscription. Like queries, subscriptions enable you to fetch data. Unlike queries, subscriptions maintain an active connection to your GraphQL server (most commonly via WebSocket). Subscriptions are useful for Low-latency, real-time update scenarios where the frontend will periodically keep polling for incremental updates. For e.g. A book added into inventory stock can be made available immediately for purchase on an online platform with the help of subscriptions.

Subscription {  
onCreate
{
id
title
}
}

GraphQL Operations [cntd..]

Now that we have seen all the operations supported by GraphQL at a high level, let’s understand the low-level implementation required for performing various operations.

Define a Schema:
The first thing we have to do is to define the schema.

{
type Country
{
id:ID!
name:String!
code:String!
}
}

the syntax starts with the type key and further the name of the schema. This schema is of type object so it starts with curly braces. And in that, we would be adding the scalar elements with their respective data types. Id would be the default GraphQL id, name as a string, and the code as a string. And mark next to the scalar types means that GraphQL will promise to give you value when you query this field. The field is non-nullable.

Write a Query:

{
countries(name:’united’)
{
name
}
}

In the write query, we need to define the operation with the details needed and hit the query. The result will be something like this. Although there are several other things to be performed, those we’ll see on the use case demonstration.

Get what you asked for:

{
"data":{
"Countries":[
{
"name":"United Kingdom"
}
]
}
}

Benefits of GraphQL

Strongly-typed: A GraphQL server defines a specific type system, queries are executed within this context. GraphQL requires a user-defined schema built using a strict type system. This schema acts as a blueprint for the data handled by the API, allowing developers to know exactly what kind of data is available and in what format. Developer tools can take advantage of the schema through the use of introspection, enabling documentation, query auto-complete, and mocking tools.

Exact Fetching: Since GraphQL queries can define what data exactly is needed at query time, all the data required to render an application view can be requested in a single request, reducing the number of roundtrip network requests and with that, the application latency. Hence, a single endpoint to access data, one request, only the fields that are asked

API Documentation: GraphQL provides auto-generated & in-built API documentation that always remains in sync with API changes. As the GraphQL API is tightly coupled with code, once a field, type, or query changes, so do the docs. This directly benefits developers, since they have to spend less time documenting an API.

Independent Teams: With GraphQL and it’s strictly typed schema, the front-end and back-end teams can work in parallel and independently. The schema generated from the GraphQL backend can be easily utilized by the frontend team to create queries. At the same time, the front-end team can continue working with just a mock version of the API. They can also test the code with it. This way, GraphQL ensures that the developers will have a satisfactory experience without stalling their development work.

Rapid application prototyping: If you had ever planned to develop a prototype, you would have experienced that CRUD operations can be time-consuming. GraphQL speeds up this process by providing a single API endpoint that serves as a data proxy between the UI and the data storage. The velocity of development is closely related to the improved developer experience that GraphQL offers.

Version free: Versioning of APIs is a common problem and generally, it is fairly simple to solve by adding a new version of the same APIs by appending a v2 in front of it. With GraphQL the story is different, The documentation clearly states that you should evolve your APIs meaning adding more fields to an existing endpoint would not break your API. The frontend can still query using the same API and can ask for the new field if needed.

GraphQL in Production

Here you can see, these are all the Giants that are supporting as well as using GraphQL in their production environment.

Source of Information: https://stackshare.io/graphql

No doubt you can think of using it in the use cases related to your project. It would definitely add value.

Summary

In this article, we learned about GraphQL, it’s architecture, how it works, and how to use it. In the next article, We’ll cover in detail, the GraphQL type systems along with its practical demonstration on GraphQLHub. GraphQLHub is a playground provided by Github where you can get yourself familiar with GraphQL Schemas and type systems by practicing it online.

To learn more about GraphQL Query Language, you can refer to the following article GraphQL: The Query Language.

--

--