What the duck is GraphQL?

What the duck is GraphQL?

Why do I need something better than REST APIs? GraphQL has nothing to do with ReactJs. GraphQL is an application interface (API) just like REST, which is much more powerful and flexible and can be written in pretty much any language.

Yes, that’s how I am starting this post, there has been a huge confusion among developers that GraphQL is only for React apps because it was introduced in one of the React conferences.

Facebook has been using GraphQL since 2012 internally and later on made it open source. If such a tech giant company has been using GraphQL for so long on production, GraphQL definitely deserves some attention.

Who else uses GraphQL?

From 2015 many companies have adopted GraphQL and slowly migrating it to. Coursera, Github, Twitter, Shopify are few of big names using GraphQL.

You should read the list of these case-studies sections to get some insight why few of these companies chose GraphQL and how are they planning their future relationship with GraphQL.

Companies using GraphQL in production

By now I think I am able to convince you to some extent, that you should really know more about GraphQL 😁.

Let’s continue our ice breaking session with GraphQL.

But why GraphQL? I was happy with REST

Imagine a restaurant serves only three kinds of pizzas, chicken pizza, broccoli pizza, and cheese pizza but you want a pizza with toppings of chicken, cheese, and broccoli.

If you visit RESTurant you have to order all the three pizzas throw pizza base of the two and combine the toppings of all the three pizzas.

In GraphQL restaurant, it allows you to customize and in one order you get whatever you want. This leads to no extra wait time and no wastage of pizza base.

The above analogy pretty much explains what is the fundamental difference between REST and GraphQL.

GraphQL stands for Graph query language.

Which means type your query and the API responds to your query.

You get, what you ask.

No doubt REST has solved many problems over SOAP.

REST has been helping all the companies make profits for a couple of decades now. With REST APIs everything looked perfect, but when we want to get more data in less number of API calls or fewer roundtrips from client to server, we smell a lot of stuff in the way REST API is designed.

When we look at the REST APIs with magnifying glasses we can see the scars and those scars are screaming for optimizations.

Sample API request in REST vs GraphQL

Let me share a quick example of how REST works.

In REST we have multiple well-defined API endpoints which are responsible for only one task.

Let’s take an example, imagine you want to get some details from the movie details platform and you want to know:

  • The details of the first actor from the best movie of the year 2019.

The REST APIs that we need to call is roughly the following list:

1) To get all the details of the best movie of the year 2019, you have to call:

GET /api/movies?bestOfYear=2019
Response: 
{
    id: 4,
    name: "The superAPI",
    ...,
    ...
}

2) To get the actors from the above movie, you have to call:

GET /api/movies/4/actors
Response:
[
    {
        id: 10,
        name: "Mark Zuckenburg",
        ...,
    },
    {
        id: 11,
        name: "REST",
        ...,
    },
    {...}
]

3) To get the details of the actor with id 10 you have to call one more API.

GET /api/actors/10
Response:
{
    id: 10,
    name: "Facebook"
    age: 15,
    ...,
    ...
}

And if you want more details you have to call more and more APIs 😫

The above is the real problem with REST APIs.

Whereas in GraphQL you need to call only one API, e.g

POST /api/graphql
Request:
{
    movie(category = "best", year = 2019){
        id,
        name,
        releaseYear,
        actors(limit = 1){
            id,
            name,
            age,
        }
    }
}
Response 200 ok:
{
    date: [
        id: 10,
        name: "The super API",
        releaseYear: 2019,
        actors: [{
            id: 10,
            name: "Facebook",
            age: 15
        }]
    ]   
}

And that’s it 😎

Let’s summarise a few of the problems with REST APIs

  1. Multiple roundtrips and data over fetching
  2. As in above example, we wanted the details of one actor from the best movie, there have been a couple of API calls, a lot of over fetched data which we did not want and never asked for, e.g the details of other actors.
  3. The APIs are tightly coupled with the client
  4. Imagine if you want to change some structure or URL of API, the same has to be reflected in the frontend app.
  5. If there is any single change in API and you have a web app, an android app, and ios app, all the different client apps have to be synced with API changes and redeployed, isn’t it too much?
  6. More wait time for the end user to receive the final set of data
  7. The above points are directly responsible for more wait time to receive the data.

    Benefits of GraphQL over REST API

How to write GraphQL API?

The GraphQL is the thinnest layer in the application codebase, which doesn’t contain any business logic, this layer only helps as an interface to interact with services or data sources. This layer is more like a controller layer.

The GraphQL API is built using the following main components:

  • Types

The types are the data models in GraphQL which is strictly typed. These types indirectly help in API documentation to the client.

type Actor {
  id: String!, # `!` represents required
  name: String!,
  age: Int!
}
type Movie {
  id: String!,
  name: String!,
  releaseYear: Int!,
  actors: [Actor] # Actor is another type and [] represents array of
}
  • Query

The queries are used to create an interface where the client can put their queries and GraphQL *resolves it and responds with the data. To set up the query, *GraphQL *needs to have strictly typed schema. These schemas also help in creating the documentation which helps the clients to get details what properties it can query from one *GraphQL API.

Compared to REST the query helps in writing all the GET APIs.

type Query {
  movie(category: String, year: Int): Movie # takes category and year as param and return Movie
  movies: [Movie], # equivalent to GET /api/movies
  actors: [Actor], # equivalent to GET /api/actors
  actor(id: String): Actor # equivalent to GET /api/actors/{id}
}
  • Mutation

As the name suggests, the mutations are used to create the interface through which the client can create resources or update the resources.

Compared to REST the mutations helps in writing the POST, PUT and DELETE APIs.

In the following example, we are creating a mutation which takes the name, release year and list of actors as input to create a new movie and returns the newly created movie.

Please note the Actor is ActorInput, it is another model representing the input fields of the actor.

type mutation {
 addNewMovie($name: String!, $releaseYear: Int!, $actors: [ActorInput]): Movie
}

What does it take to replace REST API with GraphQL?

Please note the mutation and query looks like the function header. We would need to define a query resolver class, and it should contain an equivalent name of the function definition to perform the task. Those functions can inject other services and interact with the data source.

I hope this gives a better understanding of how the queries are resolved.

So to answer in short you just need to replace the controller layer of your REST APIs with Query resolver and define these types and GraphQL schema. And everything from services to data source and ORM (if any) remains as it is. Isn’t it super awesome? 😎

Though this needs more details and more things are involved when migrating from REST to GraphQL, but this is the crux of it and I hope you get it.

What’s next?

There are many more topics we need to discuss in detail, follow me and keep an eye on this place. In the next few posts I will write in detail about the following topics:

  • Authentication and Authorization in GraphQL
  • How to migrate from REST APIs to GraphQL
  • GraphQl API Documentation

Please share your thoughts about this article in the comment section or share it on twitter.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

REST vs GraphQL - What's the best kind of API?

REST vs GraphQL - What's the best kind of API? Should you build/ use a REST API or a GraphQL API? Can you only use GraphQL with React? Time for a detailed comparison!