What is a GraphQL query?

Avatar

A GraphQL query is a read operation that is used to request specific data from a GraphQL server. It allows clients to specify the exact data they need from an API. Unlike requests to REST APIs, which receive a predefined set of data from a server, GraphQL queries empower you to tailor requests to your specific needs.

Within GraphQL, actions are predominantly categorized into two operation types:

  • Queries: These operations retrieve data, much like a GET request in REST.
  • Mutations: These operations alter data and are comparable to POST or DELETE requests in REST.

While some people use the term “query” to cover both GraphQL queries and mutations, the term “operation” is more encompassing of both actions. In this blog post, our emphasis will be on the query operation. We’ll also dive into a practical example using Postman’s GraphQL client.

So, buckle up as we embark on a journey to understand the power and versatility of GraphQL queries.

Related: GraphQL vs. REST

What are the key characteristics of GraphQL queries?

Before we explore how GraphQL queries work, let’s first review their three primary characteristics:

  1. Precise data fetching: You can request exactly what you need—nothing more, nothing less.
  2. Hierarchical structure: Queries mirror the shape of the data they return.
  3. Strongly typed system: GraphQL APIs are defined by a type system, ensuring you only ask for what’s possible and receive predictable results.

What do GraphQL query operations look like?

A GraphQL query is a read-only operation. It enables the user to request specific fields from objects and receive only those fields, avoiding over- or under-fetching. A GraphQL query typically consists of the following elements:

  1. Operation type: Defines the type of operation—either query, mutation, or subscription:
    graphql
    query Character{
      // Your query goes here
    }
    
  2. Field: Specifies the type of data you want to retrieve. In the example below, we’re requesting the name and gender fields for every character in the database:
    graphql
    query Character {
      character {
        name
        gender
      }
    }
    
  3. Arguments: Provides parameters to filter, paginate, or customize the query. Arguments can be of many different types. Below, we’ve completed our query by specifying the id of the character we’d like to retrieve:
    graphql
    query Character{
      character (id: 123) {
        name
        gender
      }
    }
    

How do you write a GraphQL query?

GraphQL queries can be written in three different ways, but each one serves the same functional purpose. The first approach uses the query and name keywords, as shown below:

query Character {
  character {
    name 
    gender
  }
}

You can also use the query keyword but omit the name keyword:

query {
  character {
    name
    gender
  }
}

The last option involves omitting the query and name keywords and simply beginning with a curly bracket:

{
  character {
    name 
    gender
  }
}

Although the query and name keywords are not mandatory, it is advisable to include them for two primary reasons:

  1. Distinguishing the operation type: The query keyword helps clearly identify the operation type for better code readability.
  2. Facilitating team collaboration: The combination of the query and name keywords makes it easier for other team members to understand the purpose of your query.

What do GraphQL query results look like?

A GraphQL response will mirror the structure of the query and will typically be presented in JSON format. For instance, if we were to execute the Characters query we explored above using the Rick and Morty GraphQL API, the resulting data would look like this:

GraphQL query results in Postman.

In this example:

  • The query keyword signifies a read operation.
  • Character is the main data object we’re querying, with id being an argument that specifies an individual character.
  • The fields we want to retrieve are name and gender.

What are the advantages of using GraphQL queries?

GraphQL queries offer many advantages, including:

  1. Efficient data retrieval: GraphQL queries reduce bandwidth usage and improve performance, especially in mobile networks.
  2. Flexibility: GraphQL queries easily adapt to changing frontend requirements without modifications to the backend.
  3. Strong type system: GraphQL queries help improve API reliability, as well as the overall developer experience.

How do you execute GraphQL queries in Postman?

Now that we understand the structure of queries and their anticipated responses, the next question is: how do we execute them?

Since GraphQL queries are essentially plain strings, several methods are available for fetching data. Among the numerous options, a few notable approaches include:

  • curl
  • fetch
  • GraphQL clients like Postman

Postman’s GraphQL client enables you to easily explore schemas with introspection and quickly build queries, mutations, and subscriptions to get the data you need. Follow these steps to create and execute an example GraphQL query using Postman’s interactive query builder:

  1. In Postman, select New > GraphQL to open a request in a new tab. In the Postman desktop app, you can also select ⌘+N or Ctrl+N, and then select GraphQL.
  2. In this example, we will be using Postman Echo GraphQL. In the URL bar, enter https://graphql.postman-echo.com/graphql. This will load the schema using introspection. You can also choose to load a GraphQL API from Postman or import a schema from your local system.
  3. In the query explorer on the left, select the hello field and select person, age, and name as arguments.
  4. Enter your age and name in the input boxes next to age and name. You should also see a fully-formed query based on your selections on the right.
  5. Click Query.

gif of composing and executing a GraphQL query with Postman.Composing and executing a GraphQL query with Postman.

Conclusion

In this blog post, we’ve walked through the basics of GraphQL queries and shown how to execute them with Postman’s GraphQL client. GraphQL queries offer a powerful, flexible, and efficient way to interact with your API. By allowing clients to request precisely what they need, they enable more efficient data transfer, better performance, and a more seamless development experience. Whether you’re building a complex web application or a simple project, understanding and utilizing GraphQL queries can significantly enhance your API interactions.

Learn more about working with GraphQL queries in this video:

Technical review by Doc Jones and Meena Dhanani.

What do you think about this topic? Tell us in a comment below.

Comment

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.