As a web engineer, you can’t afford not to know what GraphQL is. It is an API Query syntax for front-end and back-end communication, which significantly improves the cooperation model between front-end and back-end, and this article will introduce to you why you should learn GraphQL, and organize the three major advantages of GraphQL, so that you can understand what is different from traditional RESTful API. Of course, we are not telling developers to abandon RESTful APIs, but to decide on different technology stacks depending on the project, for example, service to service calls are not suitable to use GraphQL, but to use the lighter RESTful API or gRPC.

Okay, here are three advantages of GraphQL.

1. Reduce the number of connections

GraphQL

As you can see from the above diagram, it takes two requests to complete this page to get all the data back, that is, it takes two connections, but in GraphQL, you can write the query syntax together and send it to the backend, and then send it back to the frontend after all the processing is done.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
query {
  blog (
    id: 10
  ) {
    title
    post
    createdAt
    updatedAt
    user {
      id
      email
      username
    }
  }
  me {
    username
    email
  }
}

With the above syntax, you can get all the data directly and reduce the number of connections significantly.

2. Obtain only the necessary data

In the RESTful API world, the backend will send back all the data at once, not caring whether the frontend needs the field or not, that is, the frontend does not have the right to decide what field to take, which will cause a lot of unnecessary network transmission. Take the following diagram to illustrate.

RESTful API

In the top right corner, the front-end only needs the user’s avatar + email, but the back-end API gives back 10 fields to the front-end, but only two fields are really needed, and the other 8 are redundant. This side of the RESTful API can also return different fields of information according to different screens, but it causes a big burden on the backend. This problem is solved by using GraphQL, just define the data you want to get in the Query syntax.

1
2
3
4
5
6
7
8
query {
  me {
    username
    email
    firstName
    lastName
  }
}

3. Real-time API files

We all know that files are never updated in real time, and it’s hard to write RESTful APIs that require the backend to be updated. When the project is in a hurry, who cares whether the files are up-to-date or not, this is where GraphQL is recommended, because as soon as the code is moved, the developer can know the current API files in real time through the Client tool.

file

4. Summary

The above three points are the three advantages of GraphQL over RESTful APIs, and you can decide whether you want to use GraphQL according to different project attributes.