GraphQL variables in simple terms
Tags: graphql
Published: 2020-04-02 16:30:07

---
title: GraphQL variables in simple terms
published: true
date: 2020-03-13 13:00:57 UTC
tags: graphql
canonical_url: https://blog.logrocket.com/graphql-variables-in-simple-terms/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/i8p8n4qysgptar59q9g0.png
---
**Written by [Adhithi Ravichandran](https://blog.logrocket.com/author/adhithiravichandran/)**✏️

[GraphQL](https://graphql.org/) has recently gained the attention of several companies. It’s essentially a query language for your API and provides a great developer experience.

In previous blog posts, we learned about writing GraphQL [queries](https://dev.to/bnevilleoneill/graphql-queries-explained-in-simple-terms-4inc) using the GitHub API explorer. If you are unsure what GraphQL queries are, I recommend reading [this article](https://dev.to/bnevilleoneill/graphql-queries-explained-in-simple-terms-4inc) first, before we get started on GraphQL variables.

A GraphQL schema can contain more than just the scalar types. The two most used types are [query and mutation types](https://graphql.org/learn/schema/#the-query-and-mutation-types). To learn more about defining types in a GraphQL schema, you can read our previous post [here](https://dev.to/bnevilleoneill/defining-types-for-your-graphql-api-hm5).

[![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 variables, 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.

The GitHub explorer is a great way to write and test your queries against the API. On the left side of the explorer, you can define your queries and the right side displays the JSON output that comes back from the server. What’s great about this is the documentation explorer, on the right side. GraphQL is self-documenting, and you can browse through the complete GraphQL Schema here.

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

## Variables

In GraphQL, you can use variables to reuse the same query/mutations written by the client, with different arguments.

To get started, let’s look at a query that accepts some arguments as parameters. In this query, we are going to query for a repository name and owner id. This query requires the **name** of the repository that we are querying for and the name of the **owner** as well.

## Query without variables

```jsx
query {
  repository(name: "React", owner: "facebook") {
    name
    owner {
      id
    }
  }
}
```

## The same query using variables

Now the same query above can be written to accept dynamic values using the concept of variables in GraphQL. The client could reuse the same query to pass different arguments (name and owner). Let’s look into how it can be rewritten using variables instead.

There are three steps that need to be done when you start using [variables](https://graphql.org/learn/queries/) in your query or mutation:

1. Replace the static value in the query with **$variableName**
2. Declare **$variableName** as one of the variables accepted by the query
3. Pass **variableName: value** in the separate, transport-specific (usually JSON) variables dictionary

In the GraphQL explorer, this is the query variables section on the bottom-left:

```jsx
 query ($name: String!, $owner: String!) {
  repository(name: $name, owner: $owner) {
    name
    owner {
      id
    }
  }
}
```

## Define query variables

In the client code, you can now just pass in different values as arguments instead of reconstructing a new query. In GraphQL explorer, you can type in your query variables in the bottom-left portion of the screen titled `Query Variables`:

```jsx
{
    "name": "React",
    "owner": "facebook"
}
```

## JSON response

After defining your query variables, you can now run the query to see the JSON response as expected:

```jsx
{
  "data": {
    "repository": {
      "name": "react",
      "owner": {
        "id": "MDEyOk9yZ2FuaXphdGlvbjY5NjMx"
      }
    }
  }
}
```

## Mutations with variables

So far we learned how to write dynamic queries using variables. The same concept is applicable to writing mutations as well. Let’s write a mutation against the GitHub API, and use variable values to pass to the mutation.

I am going to write a simple mutation, to update my user status on GitHub. You can explore the documentation for this mutation from the documentation explorer.

![changeUserStatus Mutation Documentation](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/03/changeUserStatus-Mutation-Documentation.png?resize=726%2C1086&ssl=1)

We are going to write our mutation by passing arguments as variables. In our case, I am going to pass the `ChangeUserStatusInput` type as the variable input to the mutation:

```jsx
mutation updateMyStatus($input: ChangeUserStatusInput!) {
  changeUserStatus(input: $input) {
    clientMutationId
  }
}
```

## Define query variables

The `ChangeUserStatusInput` type takes in a `message` parameter, and a `clientMutationId`. This ID can be any unique number:

```jsx
{
  "input": {
    "message": "Writing a blog post",
    "clientMutationId": "101010101"
  }
}
```

## JSON response

This response indicates that the mutation was executed for the `clientMutationId`:

```jsx
{
  "data": {
    "changeUserStatus": {
      "clientMutationId": "101010101"
    }
  }
}
```

## Verify mutation occurred

The best way to verify that your mutation occurred successfully, is to query for that data and make sure it has been updated on the GraphQL server. To verify that the user status was updated with the mutation we wrote, let’s write a query against the server:

```jsx
query myStatus {
  viewer {
    status {
      message
    }
  }
}
```

## JSON response

And there you go! We can see the updated status message for the user.

```jsx
{
  "data": {
    "viewer": {
      "status": {
        "message": "Writing a blog post"
      }
    }
  }
}
```

![example ui](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/03/examplewriting.png?resize=730%2C827&ssl=1)

Alternatively, we can verify if this mutation really occurred simply by viewing my profile on GitHub. Since these queries and mutations are written against real live production data, we can validate by logging into GitHub.

You can notice the status on my profile has been updated to _“Writing a blog post”_ **.** You can try other mutations and have fun with the live data as well.

## Default variables

GraphQL also provides us a way to assign default values to the variables. The default value is used when no variable values are defined explicitly. This works just like a function taking a default value as an argument in a programming language.

## Example of default variables

Let’s look at our query example to search for a repository by the _name_ and _owner_ from the beginning of this blog post. We have now rewritten it with default variables as the query parameters.

```jsx
query repositorySearch($name: String="react", $owner: String="facebook") {
  repository(name: $name, owner: $owner) {
    name
    owner {
      id
    }
  }
}
```

When default values are provided for all variables, you can call the query without passing any variables. If any variables are passed as part of the variables dictionary, they will override the defaults.

## The benefit of variables in GraphQL

**Reuse:** The reason variables exist in GraphQL, is to allow reuse of the same queries and mutations for different sets of parameters and values. Clients can just pass a different set of variables instead of constructing a new query or mutation

**Dynamic queries:** With the use of variables, GraphQL supports dynamic queries that can change based on the variables passed to it

**Flexibility:** This also provides the developers with the flexibility they need while querying for data

## Conclusion

I hope you enjoyed learning about GraphQL variables in this article. If you are interested in further learning about GraphQL and get a big picture overview of GraphQL, you can check out my course [GraphQL: The Big Picture](https://app.pluralsight.com/library/courses/graphql-big-picture/table-of-contents) on Pluralsight.

Other GraphQL articles:  
[https://blog.logrocket.com/defining-types-for-your-graphql-api/](https://dev.to/bnevilleoneill/defining-types-for-your-graphql-api-hm5)  
[https://blog.logrocket.com/graphql-fragments-explained/](https://dev.to/bnevilleoneill/graphql-fragments-explained-hm7)  
[https://blog.logrocket.com/graphql-queries-in-simple-terms/](https://dev.to/bnevilleoneill/graphql-queries-explained-in-simple-terms-4inc)

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

Please post your comments below and share this post with your team and friends. I will see you later with another post. You can follow me on twitter [@AdhithiRavi](https://twitter.com/AdhithiRavi) for more updates.

* * *
## 200's only ‎✅: Monitor failed and show GraphQL requests in production 

While GraphQL has some features for debugging requests and responses, making sure GraphQL reliably serves resources to your production app is where things get tougher. If you’re interested in ensuring network requests to the backend or third party services are successful, [try LogRocket.](https://www2.logrocket.com/signup-lr)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/jd2amkhuiynfjf3i33qk.png)

[LogRocket](https://www2.logrocket.com/signup-lr) is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic GraphQL requests to quickly understand the root cause. In addition, you can track Apollo client state and inspect GraphQL queries' key-value pairs.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. [Start monitoring for free.](https://www2.logrocket.com/signup-lr)
* * *

The post [GraphQL variables in simple terms](https://blog.logrocket.com/graphql-variables-in-simple-terms/) appeared first on [LogRocket Blog](https://blog.logrocket.com).