How to Write a GraphQL Query
Tags: webdev, javascript, graphql, database
Published: 2023-04-12 09:52:31


#### A beginner’s guide to writing your first GraphQL query
In 2015, GraphQL was introduced by Meta as an alternative to REST APIs for building web applications and it’s safe to say GraphQL has taken the world by storm. A [recent report](https://devops.com/key-findings-from-the-2022-state-of-graphql-report/#:~:text=The%20report%20found%2047.9%25%20of,for%20third%2Dparty%20developer%20consumption.) showed that 47.9% of developers use GraphQL and that number is expected to keep rising. But what is GraphQL? How do you get started with it, and write your first query?

In this article, we’re going to be discussing the fundamentals of GraphQL, its benefits, and most importantly how to write a GraphQl query. We will walk you through the GraphQL Schema, the syntax you will need to create and execute a query, and common mistakes to avoid while writing a query. By the end of this article, you'll have a great understanding of how GraphQL works and be able to write your query with confidence. 

Without further ado, let's get started!

### Prerequisites
While this is a beginner friendly article, it's still expected that you're familiar with javascript and Object Oriented Programming. If you do not, you can still read on and follow through without sruggling, as we'll go through everything together.

## What is GraphQL
[GraphQL](https://graphql.org/) is a query language for APIs that provides a more efficient, powerful, and flexible alternative to traditional REST-based APIs. GraphQL query language is used to access, query, and modify data in databases, as well as build APIs to access the data. 

GraphQL simplifies the process of fetching and manipulating data from an API by allowing developers to specify exactly what data they need, in one request. This means fewer requests are needed to obtain the data and no over-fetching of data occurs. GraphQL also provides developers with more control over the shape of the data that is returned, so they can structure it exactly as they need.

Think of it this way. Let’s say you need to go on vacation, and you need clothes for your trip. If you’re using the RESTful approach to pack your clothes, you’d just take all your clothes with you and then sort them when you get there. Even if you had to take several trips.

However, if you had something like GraphQL to help you with the task, it would be able to fetch and pack only the specific clothes that you’d need, saving you the stress of overpacking and multiple trips. Pretty neat right?

Well, that’s exactly how GraphqL works. It helps you get specific data from a database base at once, cutting out repetitive requests and over-fetching. GraphQl shines particularly in [React](https://react.dev/) because it enables efficient data fetching which improves the performance of your React application, and it also helps you create more simplified state management which the complexity of your code.

Now that we know what GraphQL is, let’s talk about how to use it, and how to create your first query. The first thing we’ll be looking at is a GraphQL schema.

## Understanding the GraphQL Schema
Now we know that with GraphQL we can get specific data from an API, but getting that data would not be possible without the schema. GraphQL schemas define the structure and shape of the data that can be queried in a GraphQL API. Basically a schema is essentially a blueprint that defines the types of data that can be queried by a client application.

Let’s revisit the vacation analogy. A GraphQL schema is like a shopping list that’ll contail all your clothes, along with details about them. The schema will contain the type of cloth, the color, texture, and every other detail that will enable GraphQL pick the specific clothes you’d need. 

The schema has two main types of data: objects and scalars. Objects represent complex data structures with multiple fields, while scalars represent single values like strings, integers, or booleans. That may be a bit hard to understand, so let’s explain it further using an example.

Schema’s are written using schema language. Continuing wih our clothes analogy let’s draw up a schema for your wardrobe. 

```
type Wardrobe {
  shorts: String!
  shirts: String!
  dresses: int!
  underwear: {pants: draws}!
}
```

In this example, `Wardrobe` is an object type with four fields:` shorts`, `shirts`, `dresses` and `underwear`.  Shorts and shirts both have a type `String`, dresses has an `int` type, and underwear has a nested field called `pants`. `String` and `int` are examples of a scalar type, which represents a single value like a string of characters, while `underwear` is an object type with its own fields.

In addition to defining types, the schema also defines the queries and mutations that can be executed against the API. Queries are used to fetch data from the API, while mutations are used to modify data. We’re going to be focusing only on the queries part of that because, well, that’s why you’re here.

## Syntax of a GraphQL Query
The syntax of a GraphQL query is designed to be human-readable and expressive, allowing clients to request exactly the data they need from a GraphQL API. It’s easy to understand, and easier to use. 

Let’s use the schema above as an example. If we want to get just shorts in our wardrobe, here’s what the query would look like.

```
query GetClothes{
  wardrobe {
    shorts
  }
}
```

That’s exactly what a GraphQL query looks like. Now, let’s break down the different parts of the query. 

* ‘**query**’: the query keyword basically indicates that the operation is a query operation.
* ‘**wardrobe**’: is the name of the field that is being requested. In this case, it is a custom field defined in the GraphQL schema.
* ‘**shorts**’: is a subfield of the ‘wardrobe’ field being requested.

There are other things you can add to a query, like arguments, variables, and fragments, but we’ll talk about that later.

Now that you understand the syntax of a basic GraphQL query, let’s construct a query using data from a real live GraphQL API.

## Constructing a GraphQL Query
To write our first query, we’ll be using the GraphQL [Rick and Morty API playground](https://rickandmortyapi.com/graphql). The GraphQL Rick and Morty Playground is an online tool that allows developers to explore and interact with the GraphQL API for the TV show "Rick and Morty". It provides a web-based interface where developers can enter queries, see the corresponding responses, and experiment with the available data. 

To make a query, we’ll first have to take a look at the schema for the API, which is available [here](https://rickandmortyapi.com/documentation/). There’s a lot of information there about the character schema, the location schema, and the location schema. For our first query, we’re going to get the names and genders of characters in the TV show. 

Here’s what that query would look like. Remember, we’re using this playground and just writing the query on the left-hand side. You can try it out if you’d like.

```
query GetInfo {
  characters {
    results {
      name
      gender
    }
  }
}
```

As you can see, this query basically uses the “characters” field to retrieve data on all characters in the API, and then uses the “results” field to get the name and gender of each character. The name and gender fields are scalar fields that are already defined in the [GraphQL schema](https://rickandmortyapi.com/documentation/). The result of that query will be a JSON-like object, and here’s what that looks like.

```
{
  "data": {
    "characters": {
      "results": [
        {
          "name": "Rick Sanchez",
          "gender": "Male"
        },
        {
          "name": "Morty Smith",
          "gender": "Male"
        },
        {
          "name": "Summer Smith",
          "gender": "Female"
        },
        {
          "name": "Beth Smith",
          "gender": "Female"
        },
        {
          "name": "Jerry Smith",
          "gender": "Male"
        },
        {
          "name": "Abadango Cluster Princess",
          "gender": "Female"
        },
        {
          "name": "Abradolf Lincler",
          "gender": "Male"
        },
        {
          "name": "Adjudicator Rick",
          "gender": "Male"
        },
        {
          "name": "Agency Director",
          "gender": "Male"
        },
        {
          "name": "Alan Rails",
          "gender": "Male"
        },
        {
          "name": "Albert Einstein",
          "gender": "Male"
        },
        {
          "name": "Alexander",
          "gender": "Male"
        },
        {
          "name": "Alien Googah",
          "gender": "unknown"
        },
        {
          "name": "Alien Morty",
          "gender": "Male"
        },
        {
          "name": "Alien Rick",
          "gender": "Male"
        },
        {
          "name": "Amish Cyborg",
          "gender": "Male"
        },
        {
          "name": "Annie",
          "gender": "Female"
        },
        {
          "name": "Antenna Morty",
          "gender": "Male"
        },
        {
          "name": "Antenna Rick",
          "gender": "Male"
        },
        {
          "name": "Ants in my Eyes Johnson",
          "gender": "Male"
        }
      ]
    }
  }
}
```

Just like that, we’ve successfully written our first GraphQL query. But that’s not all there is to these queries. We can use these queries to target specific data with the use of arguments. For instance, if we only wanted to get the data of characters named “rick”, we’ll add an argument to the characters field, like this. 

```
query GetInfo {
  characters(filter: { name: "Rick" }) {
    results {
      name
      gender
    }
  }
}
```

In this query, we've simply added a filter argument to the characters field that specifies a filter object with a name field set to the value "Rick". This filter then restricts the results we get to characters whose name matches "Rick". That’s the beauty of GraphQL arguments: like a surgeon’s scalpel, it enables you to cut through the data and get exactly what you want. 

With that, we’ve successfully written a GraphQL query. Of course, there’s a bit more to queries like [fragments](https://graphql.org/learn/queries/#fragments:~:text=in%20one%20request.-,Fragments%23,-Let%27s%20say%20we), [variables](https://graphql.org/learn/queries/#fragments:~:text=different%20GraphQL%20requests.-,Variables%23,-So%20far%2C%20we), and [mutations](https://graphql.org/learn/queries/#fragments:~:text=completely%20new%20directives.-,Mutations%23,-Most%20discussions%20of), but you can read up on that later in your spare time. Next, let’s look at the best practices you should follow when writing GraphQL queries.

## Best practices for writing a GraphQL query
* Name all operations: In all our operations above, we gave the queries a name, i.e GetClothes, and GetInfo. The truth is, we don’t necessarily have to do so, as the queries would still work without us giving the operation a name. However, it’s best to always name your operations for clarity of purpose and to to avoid unexpected errors. 
* Be specific with your query: Only ask for the data you need. Avoid requesting unnecessary fields or data that you won't use. This will make your query more efficient and faster, which is the entire point of using GraphQL over the RESTful approach
* Avoid nested queries: While GraphQL allows for nested queries, it's best to avoid them as much as possible. They can lead to performance issues and make queries more difficult to read and maintain.
* Use the GraphiQL tool: The [GraphiQL tool](https://www.onegraph.com/graphiql) is a powerful development tool that allows you to interactively build and test your queries. You can set it up locally on your computer or use the online versions to experiment with different queries and ensure they return the expected data.

## Common Mistakes to Avoid when writing a GraphQL query
* Over-fetching or under-fetching data: Over-fetching means retrieving more data than you need, which can slow down your application. Under-fetching, on the other hand, means not retrieving enough data, which can result in multiple requests being made to the server.
* Nesting too deeply: Nesting too deeply in GraphQL can make your queries difficult to read and maintain. It is best to keep your queries shallow and only nest when necessary.

## Conclusion
If you’ve made it this far, then congratulations you’ve learned how to successfully write your first GraphQL query, and you’ve also learned the best practices and mistakes to avoid. If you’d like to learn more about GraphQL in general, you can check out this [video](https://www.youtube.com/watch?v=BcLNfwF04Kw&t=211s). It was quite useful to me when I was starting out.

I hope this article was useful to you. See you in the next one!