The what and why of GraphQL


GraphQL is a query language for APIs that allows us to write queries that define the data that we receive. But why do we need one more layer? The answer to this question lies in understanding the problem that we face once our API starts evolving. As our API evolves we add/remove new parameters and it gets consumed by different clients.


We can understand GraphQL by an analogy, first, let’s try to understand what is the purpose of SQL, SQL is a structured query language to access data from the database. If we compare REST endpoint to be a data source(aka table) then the endpoint is like a source of all the information in the resource. But there is no similar technology to query the API.

Let’s try to understand this by an example, assume that there is an API that exposes customer information.

Each customer has an order and each order has multiple line items. If we want to display order details for a customer, we need to make a call to get all orders, and then for each order, we need to make a call to get order details and for each order detail, we need to make a call to fetch line item. This is a lot of calls just to display order details.

GraphQL can provide a solution where we can query this information in a single call and its responsibility of the GraphQL server to make other calls and combine these. This will save lots of network calls.

On top of this GraphQL solves the following problems:-

Cluttered API: Every API starts clean but as it evolves, new parameters are added which is required for all clients. So effectively the client needs to fetch the details even if it’s not going to be used. This creates problem considering the wastage of network bandwidth.

Dumb endpoint: Traditional API does not have the capability to provide aggregate functionality. The endpoint has a very limited capability to store or retrieve information in different criteria.

Under fetching: It means not getting enough information in a single call and forces the client to make further calls to get full information.

Over fetching: It defines a situation where an API client fetches too much information that is not required.

Aggregator: This maps to the backend for the front end pattern. If we have multiple endpoints it becomes the responsibility of the client to aggregate these API for a single-use case.

No Contract: And last but not least is there is no intelligent contract between backend and front end to talk.

In next section, I will explain how GraphQL solves these problems with examples.

Source Code:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s