Graphql vs REST API

Graphql and Rest api both are ways of defining web API on server which can be used by client to gather the data.

Lets see the problems with the REST api and how graphql fixes it.

  1. No enforce contract:

    There is no contract between the client and server to guarantee that the endpoint's output always stays consistent. Unless there is a comprehensive documentation, its very difficult for client to know what operations are supported and what is the structure of the returned data.

    GraphQL works differently. It defines the structure of response data using the strongly typed Schema Definition Language (SDL). This helps the client understand the supported operations and data.

  2. Data Over fetching and under fetching

    REST api treats everything as a resource and each resource can be interacted with set of different endpoints. Sometimes client may require data from multiple endpoints which requires sending multiple request to server. This is called as under fetching because one endpoint is not able to provide all the details to the client.

    Similarly, there is another issue known as overfetching. It occurs when the client requests data from the server, and the server sends back more data than needed. This issue is referred to as overfetching. It often happens when using the same endpoint for both desktop and mobile apps. Mobile apps usually have limited space on the screen and cannot display all the data at once.

    On the other hand, using a GraphQL client can fetch data from multiple resources in a single query. GraphQL enables selective querying for resources and their data. This effectively solves the issues of overfetching and underfetching.