To read data with GraphQL, the client uses the query method. In the pattern of this query, the client has to explicitly specify all the object and fields it is interested in. As a result of the query, the client gets exactly the objects and fields in the response that are specified in the request. Let’s have a look at an example query.

query {
  books {
    title
  }
}

In this example, the client receives a list of books. Out of all the fields that book objects have, only the title will be returned for each book. Even though books might have other fields besides the title, these fields are not returned because they have not been explicitly requested in the query. Executing this query might result in the following data, which is returned in JSON format.

{
  "data": {
    "books": [
      {
        "title": "Book 1"
      },
      {
        "title": "Book 2"
      }
    ]
  }
}

What we first notice when using GraphQL for retrieval is that the structure of the response looks very similar to the query in the request. Query and response have the same shape. The query is comparable to a template in a template language. In the response, the client gets exactly the fields that are specified in the request, nothing additional, no surprises.

The query can also be given a name, allowing us to identify it easier later on. In the following example, we give the query the name myBookQuery.

query myBookQuery{
  books {
    title
  }
}
What is a GraphQL Query?
Tagged on: