I want to make sure I understand how GraphQL works. Here's my understanding of one way of how GraphQL is superior to RESTful APIs. Say you have a user
model:
{
user: {
firstName: "John",
lasName: "Smith",
username: "jsmith",
email: "jsmith@company.com",
gender: "M",
password: "password"
}
}
Then, you make an API call to get
this user's info for your app's profile page. Let's assume you only want the user's firstName
(maybe to display a welcome message).
axios.get(get_user_info_url).then(res => {
const firstName = res.data.user.firstName
})
So, what's happening here is that the res
from the server includes all of that user's info, which includes data that we don't care about (such as his username
and email
). That means that the server is downloading all of this user's data, and sending it back to the client. But, the client only cares about the firstName
, and basically disregards everything else. So, if the user
model has dozens (or hundreds) of attributes on it, we would be overfetching because we're downloading data that we simply don't need.
In this example, to get his first name, we have to set res.data.user.firstName
. With GraphQL, however, the server sends back only the user's firstName
, and not the rest of his info. So, with GraphQL, we are not downloading the entire user model from the server (overfetching).
Rather, we are only downloading the data that we need (like his firstName
). This would be beneficial if the user had dozens of attributes because we would only fetch/download the data that we actually need.
Is this understanding of GraphQL correct?