REST and GraphQL are technologies used to consume APIS. However, each one has their own particularity. This text aims to compare each one of them and provide a short introduction to GraphQL.
GraphQL
It is a query language for API, according to your specification. It was developed by Facebook Team to fix problems found in the REST API.
The principles of GraphQL are:
- You receive what you ask for.
Data is returned from the same fields that you request by the GraphQL query, for example:
Query example:
query {
city{
name
}
}
Query return:
{
"data": {
"city": [
{
"name": "jundiaí"
},
{
"name": "campinas"
}
]
}
}
Data is returned from the same fields that you request by the GraphQL query, for example:
const data = {
city: [
{ id: '1', name: 'jundiaí', state: 'SP' },
{ id: '2', name: 'campinas', state: 'SP' },
],
}
The objects have the fields "state" and "id", but if we don't request them in our query, the API will not return them
- You need only one request.
Unlike REST where we need to request with numerous endpoints, in GraphQL only have to do one request.
REST vs GraphQL
Over-fetching: it's very common to request using the REST API and getting too much unnecessary data and fields returned to us. As we saw, this doesn't happen with a GraphQL query.
Under-fetching: we can request from the REST API, but your response may not return the data you need, and because of that, another request to a different endpoint must be made.
Finally, GraphQL has one endpoint. This is a big advantage because REST uses too many endpoints which may be confusing.
Top comments (0)