One feature that makes GraphQL more flexible and powerful is its support for variables. By the end of this tutorial, you should have a solid understanding of how to use variables in GraphQL effectively and take advantage of their benefits.
Getting Started
Before diving into variables, we must set up our environment. For this tutorial, we will be using the Hygraph Commerce Shop template. You can clone this template and retrieve your GraphQL endpoint by following these steps:
Sign up for a Hygraph account and log in to the dashboard. Select the Commerce Shop Template and follow the prompts to create your project. Once your project is created, navigate to the Project settings section in the dashboard and copy your Content API endpoint.
With our Hygraph Commerce Shop project set up and our GraphQL endpoint retrieved, we are ready to explore variables in GraphQL.
How to Use Variables in GraphQL
Variables allow you to dynamically pass values to your queries and mutations, thereby enhancing the power and efficiency of these operations.
Syntax and Structure of GraphQL Variables
GraphQL variables are defined using the $ character, followed by a name and a type. For example, to define a variable for the email field of an order list, we would use the following syntax:
query ($email: String) {orders(where: {email: $email}) {idstagetotal}}
We would then provide a value for the variable when we execute the query. For example, to retrieve all orders with the email address john@doe.com
, we would provide the following value for the email
variable:
{"email": "john@doe.com"}
The exact way to pass variables in a query depends on the GraphQL client library that you are using. For example, if you are using the Apollo client, you can pass variables as follows:
import { gql, useQuery } from "@apollo/client";const GET_ORDERS = gql`query ($email: String) {orders(where: { email: $email }) {idstagetotal}}`;const { data } = useQuery(GET_ORDERS, {variables: { email: "john@doe.com" },});
Variable Types
GraphQL supports several built-in variable types, including:
Int
: a signed 32-bit integerFloat
: a signed double-precision floating-point valueString
: a UTF‐8 character sequenceBoolean
: true or falseID
: a unique identifier, often used as a primary key
In addition to these built-in types, GraphQL allows custom scalar types to be defined, providing flexibility in the types of values that can be passed as variables. For example, our Hygraph Commerce project custom types like DateTime
, which allows date and time values to be passed as variables.
Required Variables
We can mark a variable as required by adding the !
character after its type. If we do not provide a value for a required variable when we execute a query or mutation, the query or mutation will return an error.
Here's an example of a mutation that requires four variables, name
, price
, description
, and slug
, while the createdAt
field is optional.
mutation createProduct($name: String!$price: Int!$description: String!$slug: String!$createdAt: DateTime) {createProduct(data: {name: $nameprice: $pricedescription: $descriptionslug: $slugcreatedAt: $createdAt})}
When executing this mutation, we must provide values for the required variables; otherwise, we will receive an error. However, the $createdAt
variable is optional, and its absence won't affect the mutation's execution.
Assigning Default Values to Variables
We can also assign default values to variables, which will be used if no value is provided when the query or mutation is executed. To do this, we use the =
character followed by the default value.
For example, if we would like to load products with a price
greater than 200, we could use the following query syntax:
query ($price: Int = 200) {products(where: {price_gt: $price}) {idnamepricedescriptionpublishedAt}}
In this query, the where argument is used to filter products where the price field is greater than the value of the price variable. The $price
variable has a default value of 200, which means that if no value is explicitly passed during query initialization, the query will always return products with a price greater than 200.
Recommended reading
Passing Variables via Hygraph's GraphQL Playground
Hygraph's API playground facilitates testing GraphQL queries and mutations, including the ability to pass variables. To pass variables through this interface, switch to the Query Variables section on the right-hand side, as shown below.
Next, enter the variable(s) and their corresponding values in JSON format. For example:
{"email": "john@doe.com"}
The values from the "Query Variables" section will be automatically injected into your query or mutation. If any required variables are missing, you will be prompted to provide them before executing the query or mutation.
Conclusion
In this tutorial, we learned GraphQL variables and how to use them in queries and mutations and demonstrated their usage with Hygraph. Using variables can make our queries and mutations more powerful and efficient.