Why choose GraphQL over REST API?
Tags: graphql, api
Published: 2024-06-24 08:20:59

I have been working with full-stack development with GraphQL for almost 3 years. I found out that GraphQL is a lot complicated and requires more setup than the REST API. It also has a steep learning curve. And both the frontend and backend has to work slightly more in order to get the same things done. Despite all of these facts I would still choose GraphQL for my next project 😄. And I want to explain why and when you could decide to use GraphQL for your next project.

I was very confused in the beginning as to why anyone would use GraphQL? Even after working with it for few months I still could not understand the purpose of GraphQL. Some digging on GraphQL also did not help, I just found a high level overview which did not make much sense. In the other hand, REST API seemed a lot simpler!

This is the reason I wanted to enlighten developers out there who are still new to GraphQL and want them to understand the reason behind the existence of GraphQL.

Let us begin 🚀


## Why GraphQL?
My explanation is simple.

Adding `type` to APIs is what GraphQL does!

> For comparision, if Javascript is REST API then GraphQL could be Typescript.

And since the response data is also `typed` we know in advance what we are supposed to expect from the API request (_discussed more on **How does GraphQL work?** section below_). This enables us to pick data we want from the response and leave out the rest that we are not using unlike REST API where we cannot control the response data.

The following is a typical **endpoint** (or a query) that we use to make a GraphQL API request. And inside the `data {...}` object we can choose to remove keys that we want to exclude from the response data.

```graphql
query GetUserDetails {
  	user {
  	  	getDetails {
        	... on UserSuccess {
            	data {
                	name
                	email
                	phoneNumber
                	displayName
        	    	addresses {
                    	id
                    	name
                    	addressLine1
                    	addressLine2
                    	city
                    	state
                    	postcode
                    	country
                	}
            	}
        	}
    	}
  	}
}
``` 

## How does GraphQL work?
GraphQL starts in the backend where the backend developer creates a schema which defines the blueprint for the APIs. This schema is defined in a `.graphql` file and almost all the time we use codegeneration tool to convert these files to language specific code in our project.

Finally, in order for the frontend to work with GraphQL, frontend projects need to download and store the schema (using `Introspection`). This downloaded schema is the reason why frontend knows in advance what data we are getting from the API request. However, we do have to define GraphQL endpoints (queries and mutations) in separate files.

> NOTE: We can use NPM package like [get-graphql-schema](https://www.npmjs.com/package/get-graphql-schema) to download the schema from the backend.

The backend schema in the `.graphql` file looks something like this,

```graphql
type Query {
  login(input: LoginInput!): LoginSuccess!
}

type Mutation {
  register(input: UserInput!): RegisterSuccess!
  renewToken(input: RenewTokenInput!): RenewTokenSuccess! 
}

input LoginInput {
  email: String!
  password: String!
}

input UserInput {
  email: String!
  password: String!
  name: String!
  phoneNumber: String!
}

input RenewTokenInput {
  refreshToken: String!
}

type LogoutSuccess {
  success: Boolean!
}

type RegisterSuccess {
  userId: String!
}
```

As you can see everything is `typed`.

## Data interaction in GraphQL.
We interact with the GraphQL API from a single URL or a single endpoint `/graphql`.

For example: `http://localhost:8000/graphql`

> You can choose a different name than `/graphql` for your endpoint.

For every API request GraphQL uses POST HTTP method and provides three ways to communicate with the data.

1. query - to get the data.
2. mutation - to modify the data.
3. subscribe - For real-time updates.

 ```graphql
query GetUserDetails {
  	user {
  	  	getDetails {
        	... on UserSuccess {
            	data {
                	name
                	email
                	phoneNumber
            	}
        	}
    	}
  	}
}

mutation RenewAccessToken($input: RenewTokenInput!) {
	auth {
		renewToken(input: $input) {
			... on RenewTokenSuccess {
				__typename
				newAccessToken
			}
		}
	}
}

subscription NewUser {
    createdUser {
        __typename
        name
        displayName
        email
        phoneNumber
    }
}
```

You can checkout these articles to see how GraphQL is implemented in the frontend apps.

[Svelte and GraphQL with Authentication](https://dev.to/alishgiri/svelte-and-graphql-with-authentication-g4i)

[Flutter and GraphQL with Authentication](https://dev.to/alishgiri/flutter-and-graphql-with-authentication-42ef)

## Some terminologies in GraphQL

**Resolvers**
It is a function that gets called in the backend when we make an API request. Resolvers are auto generated code from the `.graphql` files.

**Introspection**
It is a way for the frontend to get the metadata about the schema from the backend. Using this we get the GraphQL schema on the frontend.

**Scalars**
Since GraphQL is a language (a query language) it has its own basic types like  `Int`, `Float`, `String`, `Boolean`, and `ID`. We can also register and define our own types. This is mostly useful if your backend and frontend projects are in two different programming languages. So a `data type` is a Scalar in GraphQL.

## Conclusion
You can use GraphQL for medium to large size projects. And, If you just have to built few APIs then it might not be a good idea to use GraphQL. It is just too much work.

Furthermore, GraphQL is a broad topic and one article cannot cover everything. The purpose of this article is to introduce GrapqhQL to the new comers. If you have any questions please leave a comment.