Prabhu Pant
Prabhu Pant

Reputation: 81

Why we need GraphQL when we can query for a specific field in REST?

GraphQL's principle aim is to solve overfetching problem as faced by many REST APIs and it does that by querying for only specific fields as mentioned in the query.

But in REST APIs, if we use the fields parameter, it also does the same thing. So why need GraphQL if REST can solve overfetching like this?

Upvotes: 5

Views: 1093

Answers (2)

Nir Levy
Nir Levy

Reputation: 12953

The option to fetch partial fields is only one of the key features of GraphQL, but not the only one.

One other important advantage is the 'graphic' nature of the model. By treating your schema as a graph (that is, several resources tied together by fields), it allows you to fetch a complex response, constructed of several data types in a single API call. This is a flexibility that you don't have in a standard REST API

Both these features can obviously be done by rest as well, but GraphQL gives it in a much simpler and more intuitive way.

Take a look at this post, there's a fairly good explanation there of the advantages (and disadvantages) of GraphQL.
https://www.altexsoft.com/blog/engineering/graphql-core-features-architecture-pros-and-cons/

Upvotes: 1

Shawn LaFrance
Shawn LaFrance

Reputation: 63

When you have a REST setup, you're typically returning a whole JSON representation for each endpoint. This includes all fields that you may or may not need which leads to more data usage or more HTTP calls (if you divide your RESTful API up, that is).

GraphQL on the other hand gives you exactly what you're asking for when you query with a single POST/GET request.

Upvotes: 0

Related Questions