Working with Variables and Arguments

Tutorial 3 of 5

Working with Variables and Arguments in GraphQL

1. Introduction

Goal

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.

What Will You Learn

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

Prerequisites

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

2. Step-by-Step Guide

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.

Variables

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

Arguments in GraphQL allow us to pass values into fields. This allows us to get exactly what we want from the server.

3. Code Examples

Example 1: Using Variables

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.

Example 2: Using Arguments

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.

4. Summary

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.

5. Practice Exercises

Exercise 1

Write a GraphQL query that uses a variable to get a human's name and height in meters.

Exercise 2

Write a GraphQL query that uses an argument to get a book's name and author.

Solutions

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!