Skip to main content

Command Palette

Search for a command to run...

Why you should (not) use GraphQL ?

Updated
3 min read
Why you should (not) use GraphQL ?
A

I am a software engineer who helps startups in implementing their ideas.

Recently, I read about the GraphQL which is a query language for APIs. I thought to give a try and share the experience with you.

What is GraphQL?

As described earlier, GraphQL is a query language for APIs. Basically, it gives clients the power to ask for exactly what they want.

To understand it further, consider that your backend APIs are consumed by two front-end interfaces: web and mobile. And for some reason, both interfaces require separate fields. Without GraphQL, either you need to implement two types of APIs, one for your web client and one for your mobile client, or you need to send the exact same data to both of your clients.

Problems with sending excess data:

  1. Slower API performance

  2. Increased network bandwidth

To solve this problem, GraphQL comes into play. It lets your client ask for what it wants and filters the results automatically depending on the client's needs. How do we use GraphQL?

To use GraphQL, we need to define the graphQL schema. The schema consists of types that define the fields inside it, as described in the image below.

The ! at the end of the ID present in book type makes it a non-nullable type. The Query depicts the methods that endpoints can use.

Notice how I have used the allBooks and getBook methods defined in the Query type of the GraphQL schema.

Testing via Postman:

Now, let's see how we can test the newly implemented GraphQL API. Look at the below-mentioned image. I requested three fields: title, description, and author. And the API has given me the exact same response.

Now, let's ask for some different parameters. And GraphQL has given the exact same response which we have asked for.

Problems of using GraphQL?

  1. It is hard to cache the response. Although it is possible to cache the response, it becomes difficult as clients are free to ask for whatever field(s) they want.

  2. Generally, when we use REST APIs, we find out if everything runs smoothly through the status code, but this is not the case with GraphQL. If you get an error in GraphQL, you need to parse the body.

When you should use GraphQL ?

  1. It is advisable to use GraphQL if you have a complex API.

  2. If you have multiple interfaces, using GraphQL can be a good idea.

  3. If you're worried about bandwidth, GraphQL might be a good option.

when you are getting data from multiple sources. For example, if you are making a dashboard and want to receive data from multiple services, such as a logging service, an analytics service, and a monitoring service, It is a good idea to use GraphQL so that the client can specify exactly what it wants.

I've also attached the github repository link incase you want to explore in depth.

More from this blog

Azhan's Blog

7 posts