In this tutorial, we will learn how to use variables and arguments in GraphQL queries. This knowledge will help us make our queries more dynamic and efficient.
By the end of this tutorial, you will be able to:
- Understand how to use variables in GraphQL queries
- Know how to use arguments in GraphQL queries
- Write dynamic and efficient GraphQL queries
To make the most out of this tutorial, you should have:
- A basic understanding of GraphQL
- Familiarity with JavaScript (ES6)
- An installed version of Node.js
Variables and arguments in GraphQL allow us to create more dynamic and efficient queries. Variables are values that can change, while arguments are values that we can pass into fields.
In GraphQL, we use variables to factor dynamic parts out of queries and to reuse these variables. This makes our code cleaner and easier to understand.
Arguments in GraphQL allow us to pass values into fields. This allows us to get exactly what we want from the server.
Here's an example of how to use variables in a GraphQL query:
query getBook($id: ID!) {
book(id: $id) {
name
author
}
}
In the query above, $id
is a variable. We use the :
to specify its type, ID!
, and the !
means that the id
must be provided for the query to be valid.
Here's an example of how to use arguments in a GraphQL query:
{
human(id: "1000") {
name
height(unit: METER)
}
}
In the query above, id: "1000"
is an argument passed into the human
field, and unit: METER
is an argument passed into the height
field.
In this tutorial, we learned how to use variables and arguments in GraphQL queries. We learned how variables allow us to factor out dynamic parts out of queries, and how arguments allow us to pass values into fields.
Write a GraphQL query that uses a variable to get a human's name and height in meters.
Write a GraphQL query that uses an argument to get a book's name and author.
Solution to Exercise 1
query getHuman($id: ID!) {
human(id: $id) {
name
height(unit: METER)
}
}
Solution to Exercise 2
{
book(id: "1") {
name
author
}
}
As you continue to practice, try to use variables and arguments in more complex queries.
Happy coding!