GraphQL queries explained in simple terms
Tags: graphql, webdev
Published: 2019-09-16 13:04:05

---
title: GraphQL queries explained in simple terms
published: true 
tags: graphql, webdev
canonical_url: https://blog.logrocket.com/graphql-queries-in-simple-terms/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/t5zbracarh8fdf0uvyy0.png
---
**Written by [Adhithi Ravichandran](https://blog.logrocket.com/author/adhithiravichandran/)**✏️

[GraphQL](https://graphql.org/) is a query language for your API. It was [open-sourced](https://github.com/graphql) by Facebook in 2015 and ever since then gained immense popularity as an alternative to REST. GraphQL was created to have better communication between the client and the server. In this blog post, we are going to learn what a GraphQL query is all about, and even write a few ourselves.

You can think of a GraphQL query like a GET request in REST. GraphQL queries are used to query the GraphQL server for the data that the client needs. What is interesting about GraphQL is that clients can write custom made queries based on the individual client’s needs. This means that GraphQL enables the client to ask for exactly what they want using a query and also returns a response with only what was asked. This approach gives the client more power.

To understand this further let’s explore the concepts that make a GraphQL Query.

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Getting started: Using GitHub’s public API

To demonstrate and learn GraphQL queries, I am going to use the [GitHub API](https://developer.github.com/v4/) that is available to the public. You can follow along by opening [https://developer.github.com/v4/explorer/](https://developer.github.com/v4/explorer/). Make sure you are signed in to your GitHub account to run the queries.

On the GitHub GraphQL explorer, we can start typing our queries on the left side and hit play to see the JSON response on the right side. We can also browse through the documentation of the API on the right side. The explorer is a great way to write queries against GraphQL APIs.

![githubapi](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2019/09/githubapi.png?resize=752%2C334&ssl=1)

## Fields

**A GraphQL Query is all about asking for specific [fields](https://graphql.org/learn/queries/#fields) on objects.**

A GraphQL query is composed of fields. I am going to write our first query against the GitHub API. In this query, we are querying for the field _viewer_ and within that querying for the field _name._

**_Tip_** : Hitting Ctrl+Space on the explorer, will show you all the available fields that you can query against the API.

```jsx
// GraphQL Query
{
  viewer {
    name
  }
}
```

This is the GraphQL response that we receive back. Notice here that we got back exactly what we asked for. We got back the name of the viewer in JSON format. All the responses are wrapped in the _data_ object. Great! You wrote your first GraphQL query. Let’s learn more about queries.

```jsx
// GraphQL Response JSON
{
  "data": {
    "viewer": {
      "name": "Adhithi Ravichandran"
    }
  }
}
```

## Arguments

**Arguments can be passed to the fields and nested objects in GraphQL. This helps in eliminating multiple round-trips to fetch data from the API.**

In GraphQL, we have the option to pass argument values to fields, requesting particular data. By doing so, it differs from the REST approach and eliminates the need to have multiple round-trips to multiple endpoints. Multiple round-trips to the API server can be tedious, and performance heavy. With REST, we can only pass a single set of arguments to the URL. Whereas with GraphQL, you can pass arguments to every field and nested objects, completely eliminating multiple API fetches. A single query can fetch all the data we are looking for, from the API.

Let’s now query against the _repository_ field. This field requires us to pass two arguments, _owner_ and _name._ I am passing _google_ as the owner, and you can pass any other organization of your choice as the argument. Along with this we also need to pass the _name_ of the repository.

```jsx
// GraphQL Query with Arguments
{
  repository (owner:"google", name:"WebFundamentals") {
    name
    owner {
      id
    }
  }
}
```

Our JSON response back from the server is below. We now have the _repository_ information that we requested from the server. You can play around with this query even further, by passing different sets of arguments.

```jsx
// GraphQL Response JSON
{
  "data": {
    "repository": {
      "name": "WebFundamentals",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ="
      }
    }
  }
}
```

## Alias

What if you wanted to query the same field with multiple arguments? There are times when you may be looking for information on the same field, with different sets of arguments. You can do that using Alias in GraphQL.

**Aliases help to query for the same field, with different arguments in GraphQL.**

Let’s add more to our previous query. Let’s say I want to query the same field _repository,_ but this time I want to query for the Facebook repository in addition to the Google repository. This leads to a field conflict in GraphQL. To overcome that, we introduce aliases.

```jsx
// GraphQL Query Aliases
{
  // alias "googleRepo"
  googleRepo: repository (owner:"google", name:"WebFundamentals") {
    name
    owner {
      id
    }
  }
  // alias "facebookRepo"
  facebookRepo: repository (owner:"facebook", name:"react") {
    name
    owner {
      id
    }
  }
}
```

After providing aliases, our query is now error-free and can be run. The JSON response comes back with data for both the arguments on the same field. Each response is wrapped within the alias name. We have responses inside the _googleRepo_ and _facebookRepo_ objects_._

```jsx
// GraphQL JSON Response

{
  "data": {
    "googleRepo": {
      "name": "WebFundamentals",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ="
      }
    },
    "facebookRepo": {
      "name": "react",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjY5NjMx"
      }
    }
  }
}
```

## Fragments

A useful concept while writing GraphQL queries is **fragments.** If you notice that your query has many repetitive fields in multiple areas, you can consolidate them into a reusable unit called a fragment.

**Fragments let you build multiple fields, and include them in multiple queries. It’s like a function that is also a reusable unit.**

Let’s take a look at the query below. Notice that we are querying for the same fields inside the _owner_ field multiple times. This is a good place to use a fragment.

```jsx
{
  googleRepo: repository (owner:"google", name:"WebFundamentals") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
  facebookRepo: repository (owner:"facebook", name:"react") {
    name
    owner {
      id,
      avatarUrl
      resourcePath
      url
    }
  }
}
```

We can rewrite our query to use a fragment. Fragments are created with the keyword **fragment** and can take a unique name. This is the same concept as writing a function in a programming language.

We can create a fragment called _ownerInfo._ While creating fragments we have to let GraphQL know, on which field it is created. In our case, we are creating the fragment on the _RepositoryOwner_ field. Within our fragment definition, we can include all the fields that we are querying for on the _RepositoryOwner_ object_._ We are adding _id, avatarUrl, resourcePath_ and _url_ as fields to our fragment.

You can then use the fragment within the query by using the … operator and providing the fragment’s name as shown below:

```jsx
// GraphQL Query with fragments

{
  googleRepo: repository(owner: "google", name: "WebFundamentals") {
    name
    owner {
      ...ownerInfo //fragment
    }
  }
  facebookRepo: repository(owner: "facebook", name: "react") {
    name
    owner {
     ...ownerInfo //fragment
    }
  }
}

// fragment ownerInfo for RepositoryOwner fields
fragment ownerInfo on RepositoryOwner {
  id
  avatarUrl
  resourcePath
  url
}
```

The code shown below is the JSON response after using a fragment. Notice, that there won’t be any visible changes to the response returned with the use of fragments. Fragments simply make your query look clean and readable. It has no effect on the query response that comes back.

```jsx
// GraphQL JSON Response

{
  "data": {
    "googleRepo": {
      "name": "WebFundamentals",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjEzNDIwMDQ=",
        "avatarUrl": "https://avatars1.githubusercontent.com/u/1342004?v=4",
        "resourcePath": "/google",
        "url": "https://github.com/google"
      }
    },
    "facebookRepo": {
      "name": "react",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjY5NjMx",
        "avatarUrl": "https://avatars3.githubusercontent.com/u/69631?v=4",
        "resourcePath": "/facebook",
        "url": "https://github.com/facebook"
      }
    }
  }
}
```

## Operation name

So far, we have been writing queries without providing a name to our query. Providing a name to the query will ensure readability when there are multiple queries.

**Operation name is a meaningful and explicit name for your GraphQL operation.**

Let’s give a name to our query here. We can use the keyword _query_ and provide a name of our choice.

```jsx
query repos{
  googleRepo: repository(owner: "google", name: "WebFundamentals") {
    name
    owner {
      ...ownerInfo
    }
  }
}
```

## Conclusions

I hope you enjoyed writing some GraphQL queries. If you are interested in further learning about GraphQL and getting a big-picture overview of GraphQL, you can check out my course on [Pluralsight](https://app.pluralsight.com/library/courses/graphql-big-picture/table-of-contents) on GraphQL.

**Other Resources:**  
[https://graphql.org](https://graphql.org)/  
[https://graphql.org/learn/](https://graphql.org/learn/)  
[https://www.graphql.com/](https://www.graphql.com/)

If you have any comments, please post them below and share this post with your team and friends.
* * * 
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/graphql-queries-in-simple-terms/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [GraphQL queries explained in simple terms](https://blog.logrocket.com/graphql-queries-in-simple-terms/) appeared first on [LogRocket Blog](https://blog.logrocket.com).