Course contentsShow
← Software Engineering
Lesson 809 of 1,93325. RPC and GraphQL API DesignFree lesson

Arguments and Variables

Passing arguments to fields, using variables for dynamic queries, and type safety in parameter passing.

Arguments and Variables

You'll learn how to pass dynamic input to GraphQL queries and mutations using arguments and variables.

In GraphQL, you often need to customize what data you're requesting or sending. Arguments let you pass parameters directly into fields to filter, specify, or modify what you get back. Variables make those arguments reusable and type-safe, especially important when values come from user input.

Arguments: Passing Parameters to Fields

Think of arguments like function parameters. Instead of requesting all users, you can request a specific one:

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

Here, id: "123" is an argument passed to the user field. You're saying "fetch the user with this exact ID."

Variables: Making Queries Dynamic

Hardcoding values like "123" isn't practical in real applications. Variables let you define placeholders that can be filled at query time:

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

You'd send this with separate variable data:

{
  "userId": "123"
}

The $userId: ID! declares a variable named userId of type ID, and the ! means it's required.

Type Safety in Action

GraphQL enforces that variable types match argument types. If user(id: ID!) expects an ID, you cannot pass a string where an integer is required, or omit a required variable. This prevents runtime errors and makes APIs predictable.

Key Takeaway: Arguments customize field behavior, variables make queries reusable and dynamic, and GraphQL's type system ensures parameters are passed safely and correctly.