SyntaxStudy
Sign Up
GraphQL Arguments, Aliases, and Variables
GraphQL Beginner 1 min read

Arguments, Aliases, and Variables

GraphQL fields accept arguments inline, allowing a single field to serve multiple use cases. Arguments can be scalars or input object types, and they are strongly typed—the server validates them before any resolver runs. Aliases let you request the same field multiple times with different arguments in one query by giving each occurrence a unique name. Variables externalize argument values from the query document, making queries reusable and preventing injection attacks by keeping user input separate from the query string.
Example
# ----- Arguments -----
query GetProduct {
  product(id: "42") {
    name
    price
  }
}

# ----- Aliases: two calls to the same field -----
query ComparePrices {
  cheap: products(maxPrice: 20) {
    name
    price
  }
  premium: products(minPrice: 100) {
    name
    price
  }
}

# ----- Variables (preferred in production) -----
# Query document (static, cached):
query GetUser($userId: ID!, $includeOrders: Boolean = false) {
  user(id: $userId) {
    name
    email
    orders @include(if: $includeOrders) {
      id
      total
    }
  }
}

# Variables JSON (dynamic, sent separately):
# {
#   "userId": "7",
#   "includeOrders": true
# }

# @include and @skip directives conditionally add/remove fields:
query GetProfile($withAvatar: Boolean!) {
  me {
    name
    avatar @include(if: $withAvatar)
    bio    @skip(if: false)
  }
}