GraphQL, an alternate to Rest API

Abhishek Tripathi
BYJU’S Exam Prep Engineering
5 min readJul 18, 2021

Hello everyone! In this blog, we will learn about GraphQL in a very simple and concise way. After reading this blog, you will have a better understanding of what GraphQL is and why it is better than Rest API.

First, let’s try to understand some major problems with the rest API, then it will be easier to understand why GraphQL is better:

  • Suppose you have a POST API which is giving you a large response and you need only two or three fields from that response. Yet, as we know, the entire response will be fetched which is not even required. The vice versa is also true. If, in the response, you have only two fields like user_name and address and, after a few days, you require few more fields then you need to discuss this with the backend developer to change the API structure accordingly.
  • When you working with REST than for fetch multiple data you need to hit multiple endpoints like, first of /api/users to get the data of users, second of /api/posts to fetch posts, and third of /api/followers to fetch followers of that users. On the other hand when working with GraphQL you can fetch this concrete data in single query like below:

Query:

query
{
User(id: "1004")
{
name
posts
{
post_title
}
followers(last: 3)
{
name
}
}
}

Response:

{
"data":{
"user":
{
"name": "Jack",
"posts": [
{"post_title": "This is my first post"}
],
"followers": [
{"name":"Mock"},
{"name":"Rock"},
{"name":"Monus"},
]
}
}
}

There are few other problems also which we’ll discuss later in this blog. Now let’s understand what is GraphQL and how it has overcome these problems.

What is GraphQL? :

GraphQL is a query language provided by Facebook in 2015. It is not specific to any single platform. It works with all platforms like Android, iOS or Web.

Advantages of GraphQL:

  1. The main advantage of GraphQL is that it is very easy to learn and implement. Only few steps are required to implement it in any Android Application. One more advantage is that it is not specific to any application architecture.
  2. You will only get what you want, no more and no less. You can see in the example below that you are getting only the data you are asking in the query.

Only title required:


{
todos {
title
}
}

Response:


{
“data”: {
“todos”: [
{
“title”: “New Test”
}
]
}
}

Now if id is also required along with title then just add it in query.

{
todos {
title
id
}
}

Response:


{
“data”: {
“todos”: [
{
“id”: 571
“title”: “New Test”
}
]
}
}

As you can see in the above example, if you are using GraphQL then whatever data you want you just need to add it in the query and you will get the desired response. Now you can compare this with the REST API and experience the advantage.

3. Avoid Multiple API Calls: As we already discuss above, we can fetch multiple type data (user_data, post_data, followers) in single query.When you work with REST you need to hit three API for this.

4. Less Dependency on Backend Developer:
When you use GraphQL , for every change in the API structure, you don’t have to connect with the backend developer.

5. Many free tools and extensions are available to write queries very easily and effectively.

Steps to implement:

Step 1: Add Dependencies

Add below dependencies in the project level Gradle file.

classpath 'com.apollographql.apollo:gradle-plugin:0.3.2'

Now go to the app level Gradle file and add the following lines on the top of it

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.apollographql.android' (Add This one)

Now inside dependencies add the following:

implementation 'com.apollographql.apollo:apollo-runtime:0.3.2'
implementation "com.apollographql.apollo:apollo-android-support:0.3.2"

Step 2: Download the schema

Schema file defines the structure of your entire data and it also helps in writing queries.

To download the schema first install apollo-codegen

  • npm-install apollo-codegen //For installing the apollo-codegen
  • apollo-codegen download-schema http://yourserver/graphql--output /Users/Abhishek/Desktop/GraphqlFiles/schema.json

Step 3: Create your query

query FindToDo($toDoId:String!){
todos(todoId:$todoId) {
created_at
id
title
user
}
}

Now create a folder with the name “graphql” under the /main of your project and copy both file schema and query file to this folder. Then rebuild your project and you will get auto generated model against your query in build/generated.

Step 4:

Now it’s time to setup the apollo client

private fun setupApollo(): ApolloClient {
val okHttp = OkHttpClient
.Builder()
.addInterceptor({ chain ->
val original = chain.request()
val builder = original.newBuilder().method(original.method(),
original.body())
builder.addHeader("Authorization"
, "Bearer " + BuildConfig.AUTH_TOKEN)
chain.proceed(builder.build())
})
.build()
return ApolloClient.builder()
.serverUrl(BASE_URL)
.okHttpClient(okHttp)
.build()
}

You have added all the dependencies like header, base_url to your apollo client. Now just use this apollo client to hit the query you write and get the response like below:

client=setupApollo()
client.query(FindQuery //From the auto generated class
.builder()
.todoId(model.gettoDoId()) //Passing required arguments
.build())
.enqueue(object : ApolloCall.Callback<FindQuery.Data>() {
override fun onFailure(e: ApolloException) {
Log.info(e.message.toString())
}
override fun onResponse(response: Response<FindQuery.Data>) {
Log.info(" " + response.data()?.repository())
runOnUiThread({
//This is your required data
textViewID.text = response.data()?.todos?.id()
textViewTitle.text = response.data()?.todos?.title()
textViewUser = response.data()?.todos?.user()
})
}

Setup your UI according to your requirement and your module is ready with the above steps.

Now let’s see what options you have in GraphQL like Get, Post, Put which we have in Rest Api:

  1. Query: Query is just like Get api in Rest. When you just want to fetch the data from the server like we have done above.
  2. Mutation: Mutation is not different in terms of syntax from the Query but when we want any kind of modification at the backend like add any user data or update any user data then we use mutation.
  3. Subscriptions: When we want any kind of real-time update in the data like socket connection then we use Subscription.
  4. Fragment: When we want to share any piece of information between multiple Query then we use Fragment. You can understand fragments same as functions in programming which you write once and use anywhere.

Conclusion:

In this blog, I have given you an overview of GraphQL. Now, it’s your time to explore more. Happy Coding!

References:

https://hasura.io/learn/graphql/android/introduction/
https://www.apollographql.com/docs/android/

--

--