GraphQL was internally developed by Facebook in 2012 and was later open sourced in 2015. The idea came up when facebook needed to rebuild its mobile native application, Facebook needed a data-fetching API powerful enough to describe all of Facebook yet simple enough to be easy to learn by their developers, now graphql powers tech giants like Netflix, Twitter, Shopify etc.
Now wondering what it is about graphql that outweighs rest, well lets get on with it.
Data fetching is one of the obvious reasons we use api's, graphql makes data fetching easier by only exposing one endpoint to access data from the server, unlike rest where we have to make multiple requests to multiple endpoints.
As said earlier, Graphql exposes only one endpoint which reduces trips and network requests to the server to fetch data, while Rest exposes multiple endpoints and increases trips and network requests to the server.
As you can see in the image above, to grab a users profile, users posts and users followers with graphql we only make a request to the server while we make 3 requests to the server using rest apis to grab all the data we need.
- Graphql is a declarative data fetching specification and query language. we only fetch what we need from the server by constructing our query to only include what we need.
- Rest apis gives you more or less data than is needed for the client at a point. This makes the server spit unecessary data that would not get used by the client, therefore making uneccessary requests.
When the arise for addition of new features come in, you can easily add additional fields, queries, mutations etc to the server and other parts would not be affected, also it is easier to remove old features and make them backward compatible without any breaking changes.
Graphql can be a life saver when when building scalable applications, but you do not need to rewrite or migrate applications that have been designed to use REST api. Rather you should plan to use GraphQL for future applications.
REST for sure is not going anywhere soon. For most small applications, there would not be significant increase in performance over REST, the real magic of GraphQL plays in as applications scale and the application becomes bigger.