Skip to main content

GraphQL variables in simple terms


GraphQL 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 queriesusing the GitHub API explorer. If you are unsure what GraphQL queries are, I recommend reading this article 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. To learn more about defining types in a GraphQL schema, you can read our previous post here.

Getting started using GitHub’s public API

To demonstrate and learn GraphQL variables, I am going to use the GitHub API that is available to the public. You can follow along by opening 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.

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

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 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:
 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:
{
    "name": "React",
    "owner": "facebook"
}

JSON response

After defining your query variables, you can now run the query to see the JSON response as expected:
{
  "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
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:
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:
{
  "input": {
    "message": "Writing a blog post",
    "clientMutationId": "101010101"
  }
}

JSON response

This response indicates that the mutation was executed for the clientMutationId:
{
  "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:
query myStatus {
  viewer {
    status {
      message
    }
  }
}

JSON response

And there you go! We can see the updated status message for the user.
{
  "data": {
    "viewer": {
      "status": {
        "message": "Writing a blog post"
      }
    }
  }
}
example ui
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.
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 on Pluralsight.

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1 ...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...