Why GraphQL is better than REST
A typical client application needs to modify state or get state form the server. In the REST pattern, the client makes http requests to various server endpoints. The client code just contains the name of the endpoint and the parameters needed by it while the server-side code contains the actual documentation and logic. To allow the user to modify or get a different subset of state, the developer adds new endpoints to the server side. However, the server and system itself does not understand the schema of the state.
In GraphQl, the developer specifies a schema on the server side. A sample schema for a book and an author is provided below. All the client has to do is look at the schema to understand what requests can be made. In GraphQl, all requests are made through one endpoint in the GraphQl query language. Although the server side knows the schema of the state, it needs to define resolvers, actual mechanisms to modify the data. These resolvers can be calls to databases or even AWS lambda functions.
type Book{
id: Int!
title: String
author: Author
}type Author {
firstName: String
lastName: String
books: [Author]
}
Providing a schema to the system provides numerous advantages. In a typical REST scenario, developers would have to provide endpoints for each possible data access pattern on the server side and then call the right one on the client side. In GraphQl, because the server knows the schema and the corresponding resolvers, it can automatically handle all data access patterns. In fact, in GraphQl, clients can easily chain together multiple fields together in one request. For instance, given a book, the client could easily find all books written by the same author in a simple 3 line query.
book(id:10) {
author {
books
}
}Furthermore, the state mutations or requests are all encoded on the client side. This prevents client developers from having to modify server-side code or look at server-side endpoints to understand client side code. Finally, because the system understands the schema, it can statically detect whether a given query request is valid.
