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

Query Arguments and Variables

Pass dynamic values to queries using arguments and reusable variables for flexible data fetching.

Query Arguments and Variables

You'll learn how to make GraphQL queries flexible and reusable by passing dynamic values through arguments and variables instead of hardcoding them.

The Core Idea

Imagine ordering food at a restaurant. You don't want the menu hardcoded to "cheeseburger, medium-rare" — you want to specify what you want when you order. GraphQL arguments let you pass values directly into queries, while variables let you separate those values from the query structure, making them reusable and safer.

You've already seen arguments in queries (passing values after field names). Now you'll use variables to make those values dynamic instead of hardcoded strings.

How Variables Work

Instead of writing this (hardcoded):

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

You define a variable at the operation level:

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

Then pass the variable separately (in your GraphQL client or playground):

{
  "userId": "123"
}

Why This Matters

Variables make queries:

  • Reusable: Same query structure, different values
  • Type-safe: The ID! declares the expected type and that it's required
  • Secure: Prevents injection attacks by separating data from structure
  • Cacheable: Tools can cache query structures separately from their values

Think of variables as function parameters — they're placeholders that get filled in at runtime.

Key Takeaway: Use variables with the $name: Type syntax to pass dynamic values into query arguments, keeping your queries flexible, type-safe, and reusable across different contexts.