0
0
GraphQLquery~5 mins

Query variables in GraphQL

Choose your learning style9 modes available
Introduction

Query variables let you send values to a GraphQL query separately. This keeps queries clean and easy to reuse.

You want to get data for different users without rewriting the query.
You need to send user input like search terms or filters to a query.
You want to avoid repeating the same query with only small value changes.
You want to keep your queries safe from mistakes by separating data from query structure.
Syntax
GraphQL
query QueryName($variableName: Type!) {
  fieldName(argument: $variableName) {
    subField
  }
}

Variables start with a $ and are declared in parentheses after the query name.

Type must be specified and can be required (with !) or optional.

Examples
This query gets a user by their ID, which is passed as a variable.
GraphQL
query GetUser($id: ID!) {
  user(id: $id) {
    name
    email
  }
}
This query searches books by title. The title variable is optional.
GraphQL
query SearchBooks($title: String) {
  books(title: $title) {
    title
    author
  }
}
This query gets posts with a limit. The variable has a default value of 5.
GraphQL
query GetPosts($limit: Int = 5) {
  posts(limit: $limit) {
    title
    date
  }
}
Sample Program

This query fetches a user with ID 123 using a variable called userId.

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

# Variables:
{
  "userId": "123"
}
OutputSuccess
Important Notes

Always declare variables with their types in the query.

Pass variables separately when sending the query to keep it reusable.

Variables help prevent errors and improve security by separating data from query code.

Summary

Query variables let you reuse queries with different data.

Declare variables with types after the query name.

Send variable values separately when running the query.