TIL GraphQL vs Rest
POSTED ON:
I'm pretty happy overall with my API experiences, especially coming from a world where APIs was rare.
So when I learned about GraphQL a few years ago, I struggled to figure out 'why'?
But this post convinced me of the features. Stop Using REST For APIs
Let’s say, for example, we are displaying a user’s feed with a list of the user’s post and his/her followers.
In our case, we have to display the author of the post, the posts as well as the followers for that user.
If we were to use REST, we would have made at least 2 or 3 requests, similar to this:
/user/<id>
to get the User(Author) details likely the name.
/user/<id>/posts
to get the list of posts posted by that user.
/user/<id>/followers
to get the list of followers for the user.
But in all these cases we are over-fetching the data.
For example, in the first request, we need only the name, but we get all the details about the user when we use this approach.
This is when GraphQL shows it’s power. We need to specify the query and we can get the desired output.
To achieve the same using GraphQL, we can use a query similar to this:
query {
User(id: '123') {
name
posts {
title
}
followers {
name
}
}
Tl;dr - sometimes you need to combine API calls to get the exact data you need. If the API author swapped over to a graphql format, it'll be easier to filter the data you do need.
For a clearer example of it all:
REST APIs #
Benefits of REST
- REST is scalable, as it separates the client and server so that you can scale your application with ease.
- Flexibility is one other advantage of using REST, as it can be designed to handle different types of calls and return different data formats.
Limitations of REST
- Over-fetching — This is when the API endpoint provides way more information than required by the client.
- Under-fetching — This is when the API endpoint doesn’t provide all of the required information. So, the client has to make multiple requests to get everything the application needs.
GraphQL APIS #
Benefits of GraphQL
- Retrieve precise data, and nothing extra. In GraphQL, you get what you request, which is a great plus.
- Faster development in the Client. Usually, when there are changes in the data requirements, you would just need to modify the query and there isn’t much change required, thus allowing rapid product iterations. Both the client and server teams can work independently, provided that both the teams know the structure of the data.
Limitations of GraphQL
- Can be a bit complex for simple applications, to set up types, queries, etc, as it can be done easily using REST.
- It uses a single endpoint instead of following the HTTP specification for caching. Caching at the network level is important as it can reduce the amount of traffic to a server.
Related TILs
Tagged: api