GraphQL: What, Why, and When?

Subrat Thakur
8 min readOct 13, 2021

--

What is GraphQL?

GraphQL is a query language API developed by Facebook. It is a more efficient, powerful, and flexible alternative to REST. Unlike REST, GraphQL is more of a client-driven architecture where a client can specify exactly what data it needs from an API. GraphQL server only exposes a single endpoint and enables declarative data fetching.

What is wrong with REST? I am happy with my REST architecture.

Relax! There is nothing wrong with REST architecture. Even when we talk or think about APIs or API design architecture, one of the first things which come to our mind is REST API (also known as RESTful API). Over the past decade, REST has become the standard for designing web APIs because it offers some great ideas, such as stateless servers and structured access to resources. As per the State of API 2020 Report, 82% of the surveyed API practitioners and consumers use the REST-based OpenAPI specification, while only 19% use GraphQL.

But at the same time just like other great technology it comes with some downsides and a few of them are listed below:

  • Over-Fetching or Under-Fetching: It fetches all data, whether required or not, and sometimes not all required data in a single API call.
  • Multiple network requests: To fix under-fetching, we need to make multiple network requests to get multiple resources.
  • Waterfall network requests: When resources are dependent then it sometimes causes Waterfall network requests.

How GraphQL is different from REST? Tell me more!

Let’s try to understand this by looking into GitHub APIs.
GitHub is one of the biggest users of GraphQL architecture. GitHub chose GraphQL for its API v4 for the ability to define precisely the data people want and only the data they want, which is a powerful advantage over the REST API V3.
Consider that we want to retrieve a pull request along with its commits, non-review comments, and reviews using the REST API requires four separate calls:

curl -v https://api.github.com/repos/:owner/:repo/pulls/:number
curl -v https://api.github.com/repos/:owner/:repo/pulls/:number/commits
curl -v https://api.github.com/repos/:owner/:repo/issues/:number/comments
curl -v https://api.github.com/repos/:owner/:repo/pulls/:number/reviews

At the same time if we choose GraphQL API to fetch the same data, it can be done with a single request using nested fields:

{
repository(owner: "octocat", name: "Hello-World") {
pullRequest(number: 1) {
commits(first: 10) {
edges {
node {
commit {
oid
message
}
}
}
}
comments(first: 10) {
edges {
node {
body
author {
login
}
}
}
}
reviews(first: 10) {
edges {
node {
state
}
}
}
}
}
}

You can see how several API calls can be reduced to just one to get the same amount of data if we use GraphQL over REST.

PS: This example is taken from GitHub GraphQL documentation.

Before moving ahead, I just wanted to tell you that this article is not in favor of GraphQL or trying to convince you that GraphQL is better than REST. We are here to understand the concept of GraphQL so that at the end of this article we will be in a position to decide the most suitable API solution for your app.

What about Performance? Is GraphQL API calls faster than REST API?

GraphQL queries themselves are not faster than REST queries, but GraphQL queries do not waste bits over the wire and always aim for the smallest possible request. This is unlike REST, where additional data is often returned, even when that data isn’t necessary. Even if a REST API returns only a basic partial, it is still transferring more data.

One of the common scenarios with REST which we already talked about earlier is API chaining to fetch the required data which is not the case if you use GraphQL. In GraphQL it's simplified by enabling the server to combine all the data for the client within a single query. And that way its performance is considerably better than REST APIs.

GraphQL vs. REST performance debate may seem in favor of GraphQL, but there are some scenarios where RESTful APIs are a better option. For example, in cases where caching is desired to expedite API calls, REST APIs can perform better. REST APIs leverage the built-in HTTP caching mechanism to return cached responses faster. On the other part, GraphQL always has to fetch data from the source. GraphQL also has some options for caching, but they are way behind REST’s level.

Enough of this REST vs GraphQL! Let's start thinking in GraphQL :)

Let’s change the way we used to think about APIs and trust me, GraphQL APIs are different but pretty simple. I am going to drop some points here which will help you to understand more about GraphQL:

  • Single API endpoint: Instead of making different API calls to different URLs to fetch data, we're making ad-hoc queries to a "single GraphQL URL endpoint" that returns data based on the query.
  • POST a query: Instead of 'GET'ing a resource you 'POST' a query that describes what data you want.
  • Query Language: The "query" you send as data in the POST request has a structure and syntax. This "language" is called GraphQL.
  • Why Graph? : The data API returns as a "graph" and this allows us to make queries to fetch "related" pieces of data in a single shot.
  • HTTP Status Code: Every GraphQL request, success, or error should return a 200. Errors are handled as part of the response body under a special errors object and the client-side tooling will help in handling it better.
  • GraphQL analogs: Fetching data objects in GraphQL is called “query” whereas inserting/updating/deleting data is called “mutation”. It has one more type which is watching and subscribing to data known as “subscription”.

Schema and Type System

One question which might have been coming to your mind is “How does GraphQL understand what data can be queried ?

GraphQL query language: The GraphQL query language is basically about selecting fields on objects. And the query closely matches the result of that query. Every GraphQL service defines a set of types that completely describe the set of possible data you can query on that service. Then, when queries come in, they are validated and executed against that schema.

GraphQL schema language: GraphQL services can be written in any language. But we can not rely on any specific programming language to define the schemas and that's why we use GraphQL schema language. It is very similar to query language and allows us to talk about GraphQL schemas in a language-agnostic way.

Ex: This is an example of schema defined for object Post and Person.

type Post {
title: String!
author: Person!
}

type Person {
name: String!
age: Int!
posts: [Post!]!
}

If we start analyzing the above schema, Post and Person are GraphQL Object Type, meaning it is a type with some field that can be used while querying. title and author are fields of Post object.

title field of object Post is of type String. But what is the meaning of String! ? It means that the field is non-nullable, meaning that the GraphQL service promises to always give you a value when you query this field. Same way [Post!]!type for filed posts of object Person , represents an array of `Post` objects. Since it is also non-nullable, you can always expect an array (with zero or more items) when you query the `posts` field. And since Post! is also non-nullable, you can always expect every item of the array to be an `Post` object.

There is a lot more but I think this is enough for now, to understand how GraphQL queries can be built and how it works.

When to use GraphQL?

GraphQL works best for the following scenarios:

  • When you are designing UI/UX rich apps for devices where bandwidth matters like mobile phones, smartwatches, and IoT devices.
  • Apps where nested data needs to be fetched like a blog application or social media app where posts need to be fetched with comments and commenters details.
  • If you are developing a composite pattern application where your app retrieves data from multiple storage APIs, you should use GraphQL. A good example of it is when your app probably collects data from multiple sources like REST APIs, MongoDB, and maybe from other databases.
  • When you want to add functionality on the top of your old APIs using Proxy patterns. For example consider you want to authentication to your existing old public API. We can easily do that by putting the existing API behind a firewall, whitelist our GraphQL server and then add the authentication logic to the GraphQL server.

When not to use GraphQL?

  • When you love REST. GraphQL is an effective alternative to REST, but if you have a stable RESTful service, there’s probably not a strong case to chuck all of that workout. It’s stable and tested.
  • Learning Curve: When you are aiming to develop a simple application with a couple of fields, GraphQL can overcomplicate your use by adding stuff like — types, queries, resolvers, mutators, and other high order components. Learning and doing things in a plain REST architecture is easier.
  • Caching: It’s not a good idea to go with GraphQL if you wanted to use a web cache to cache responses. With REST APIs, all the GET endpoints can be cached at the server-side or using a CDN. They can be cached by the browser as well and bookmarked by the client for frequent invocations. GraphQL doesn’t follow the HTTP spec and is served over a single endpoint, usually (/GraphQL). Hence the queries cannot be cached in the same way as REST APIs. However, caching on the client-side is better than REST because of the tooling. Some of the clients implementing caching layer (Apollo Client, URQL) make use of GraphQL’s schema and type system using Introspection to allow them to maintain a cache on the client-side.

Disadvantage of GraphQL

  • GraphQL Rate Limiting: In REST API, you can simply specify that we allow only this amount of requests in one day”, but in GraphQL, it is difficult to specify this type of statement.
  • No Error Code for failed APIs: Since it always returns an HTTP status code of 200, whether the request is successful or not, this may complicate error reporting and API monitoring.
  • Lacks built-in caching capabilities
  • Lacks extensive adoption and support
  • Support only JSON representation.

Conclusion

GraphQL vs REST, which is better? This question is extremely subjective. Instead of deciding which one is better, we should decide which one will be more suitable for your application based on your project requirements. If you want to use a tried-and-proven technique that comes with robust native caching or authentication capabilities, then definitely REST could be your best option. On the other side if you want a more flexible option in terms of response and want to overcome the major shortcomings of REST then you can choose GraphQL.

Resources

--

--