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.
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.
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 { repository(name: "React", owner: "facebook") { name owner { id } } }
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:
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 } } }
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" }
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" } } } }
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.
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 } }
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" } }
This response indicates that the mutation was executed for the clientMutationId
:
{ "data": { "changeUserStatus": { "clientMutationId": "101010101" } } }
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 } } }
And there you go! We can see the updated status message for the user.
{ "data": { "viewer": { "status": { "message": "Writing a blog post" } } } }
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.
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.
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.
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
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.
LogRocket is like a DVR for web and mobile 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.Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowconsole.time is not a function
errorExplore the two variants of the `console.time is not a function` error, their possible causes, and how to debug.
jQuery 4 proves that jQuery’s time is over for web developers. Here are some ways to avoid jQuery and decrease your web bundle size.
See how to implement a single and multilevel dropdown menu in your React project to make your nav bars more dynamic and user-friendly.
NAPI-RS is a great module-building tool for image resizing, cryptography, and more. Learn how to use it with Rust and Node.js.
3 Replies to "GraphQL variables in simple terms"
Testing variables in some application is pretty straightforward. However, how do you use variables in a standard fetch call using code?
In the body of the request stringify your graphql query like this:- hope it helps
fetch(‘https://api.hashnode.com’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
Authorization: ”,
},
body: JSON.stringify({
query:
‘mutation createStory($input: CreateStoryInput!){ createStory(input: $input){ code success message } }’,
variables: {
input: {
title: ‘What are the e2e testing libraries you use ?’,
contentMarkdown: ‘# You can put Markdown here.\n***\n’,
tags: [
{
_id: ‘56744723958ef13879b9549b’,
slug: ‘testing’,
name: ‘Testing’,
},
],
coverImageURL:
‘https://codybontecou.com/images/header-meta-component.png’,
},
},
}),
})
.then(res => res.json())
.then(res => console.log(JSON.stringify(res)))
Thank you! After endless hours trying to use string interpolation to inject my $token into the GraphQL request and having to deal with needing to escape quotation mark characters, this helped me correctly use variables for my request.