GraphQL

What is GraphQL?

GraphQL is a Graph Query Language, it is designed for building API. It was developed by Facebook and being maintained by many companies. Since the birth of GraphQL, it is believed to be a REST replacement because of its performance.

What does GraphQL offer?

REST replacement

The problem REST is facing is that it returns too little or too much of its response. In both cases, the performance of the application is affected quite a bit. The solution that GraphQL offers is to allow data declaration where a client can determine exactly the data they need from an API.

Schema and types

GraphQL has a separate system for it that is used to define the schema of an api. All types listed in an API are written in the schema using the GraphQL Schema Definition Language (SDL).

This schema is used as a transactional copy between the client and the server to determine how the client can access the data. Then the frontend team can mock the data to test the components, while the back-end team also prepares the necessary work on the server side. Here is an example of how we can use SDL to specify User and Message types:

type User @model {
  id: ID! @isUnique
  name: String!
  messages: [Message] @relation(name: "MessagesFromUser")
}

type Message @model {
  id: ID! @isUnique
  text: String!
  sentBy: User! @relation(name: "MessagesFromUser")
}

As you can see, the User has 4 fields: id, name and messages. The “!” Sign means that the field must be entered. @model is defined as a model in the database. @isUnique means that the field cannot overlap. The required ID value is a 25-character string. ID fields are system-defined fields and are only used internally, so new fields with ID type cannot be created. With GraphQL it is possible to create associations between types. So User has the messages field which is an array of Message and similar to Message, it has sentBy field associated with User table. From the above example we have also created one or more relationships between User and Message.