5.6 Anatomy of a GraphQL Request

A GraphQL request always starts with at least one ‘root’ API operation and ensues with some finite number of follow-ups. These follow-ups serve as queries, meaning they retrieve data without changing the server in any meaningful way. GraphQL models all API operations as fields; these fields are split into two types:

  • Scalars: Scalars represent the individual pieces of data that the server will eventually deliver to the client. These are the leaves of the request tree, and the data stored in these leaves can be arbitrarily complex.

  • Objects: Objects are a collection of fields and serve as a junction in the tree. Objects do not return any data, but route the client to the appropriate scalars that the client is interested in.

The entire model for a given GraphQL API is known as its schema, and, in contrast to a REST API, it is strongly-typed. Every schema possesses a route query type, whose fields serve as the API’s entry points. An example of this is shown below.

  type Query {
               user(id: ID): User
               image(url: Url): Image
               # … a whole bunch more root fields
            }

            type User {
    name: String
    nickname: String
    image: Image
}
            
            type Image {
                url: String
                width: Int
                height: Int
          }

Figure 5.6.1: GraphQL Schema.

A GraphQL query begins by mentioning at least one of the fields of the root query object, and the aforementioned field can be utilized to specify any follow up queries. It is important to note that any field in the request tree can take arguments, so a request can be parametrized at all depths. An example query is shown below:

  {
      user(id: “10”) {
               name
               nickname
               image {
                 url
         }
            }
         } 

Figure 5.6.2: GraphQL Request.

Here the client is instructing the server to look up a user by the user’s slug (the ID), returning specifically the user’s their name, nickname, and image URL, executing the entire request in one trip instead of the two this request would have required using REST. GraphQL achieves this improved efficiency because of resolvers which are worth mentioning in additional detail.

Last updated