DEV Community

Cover image for GraphQL variables in simple terms
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

GraphQL variables in simple terms

Written by Adhithi Ravichandran✏️

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 queries using 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.

LogRocket Free Trial Banner

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
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

JSON response

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

{
  "data": {
    "changeUserStatus": {
      "clientMutationId": "101010101"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

JSON response

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

{
  "data": {
    "viewer": {
      "status": {
        "message": "Writing a blog post"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

Other GraphQL articles:

https://blog.logrocket.com/defining-types-for-your-graphql-api/

https://blog.logrocket.com/graphql-fragments-explained/

https://blog.logrocket.com/graphql-queries-in-simple-terms/

Other resources:

https://graphql.org/

https://graphql.org/learn/

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 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.

Alt Text

LogRocket 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.


The post GraphQL variables in simple terms appeared first on LogRocket Blog.

Top comments (0)