Course contentsShow
← Web Development
Lesson 1528 of 2,98228. GraphQL FundamentalsFree lesson

Variables in Operations

Parameterizing queries with variables instead of hardcoding values directly in the query string.

Variables in Operations

You'll learn how to pass dynamic values into GraphQL queries using variables instead of hard-coding them directly.

Why Variables Matter

So far, you've probably written queries with arguments like this:

query {
  user(id: "123") {
    name
    email
  }
}

The problem? Every time you need a different user, you'd have to rewrite the entire query string. This creates security risks, complicates caching, and makes your code messy.

How Variables Work

Variables let you separate the structure of your query from the data you're passing in. Think of it like a function that accepts parameters—you define what those parameters will be called and what type they should be, then pass in actual values separately.

Here's the same query using variables:

query GetUser($userId: ID!) {
  user(id: $userId) {
    name
    email
  }
}

The variables are passed as a separate JSON object:

{
  "userId": "123"
}

The Anatomy

  • Operation name (GetUser): Optional but recommended for debugging
  • Variable declaration ($userId: ID!): Defines the variable name, type, and whether it's required (!)
  • Variable usage (id: $userId): Where you actually use the variable in your query

Real-World Analogy

It's like a mail-merge template. The letter's structure stays the same, but you can insert different names and addresses without rewriting the entire letter each time.

Key Takeaway: Variables parameterize GraphQL operations, making queries reusable, safer, and easier to maintain by separating query logic from dynamic data values.