Variables, Arguments & Directives
GraphQL variables let you pass dynamic values into queries and mutations without string interpolation. Directives let you conditionally include or skip fields at query time.
1 Query Variables
GraphQL — Variables Syntax
# Define variables with $ prefix in the operation signature
query GetUser($userId: ID!, $includeInactive: Boolean = false) {
user(id: $userId) {
name
email
posts(includeInactive: $includeInactive) {
title
status
}
}
}
# Variables are passed as a separate JSON object
# (sent alongside the query in the POST body)
{
"userId": "42",
"includeInactive": true
}
# Mutation with variable
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id title createdAt
}
}
# Variable values:
{
"input": {
"title": "My First Post",
"body": "Content here...",
"tags": ["graphql", "tutorial"]
}
}
2 Built-in Directives
GraphQL — @include and @skip Directives
query GetProfile($withPosts: Boolean!, $skipEmail: Boolean!) {
me {
id
name
email @skip(if: $skipEmail) # omit field if true
posts @include(if: $withPosts) { # only include if true
title
createdAt
}
}
}
# Variables:
{ "withPosts": true, "skipEmail": false }
# Custom directives (defined in schema)
type Query {
secretData: String @deprecated(reason: "Use newSecretData instead")
newSecretData: String
}
3 Inline Fragments for Union Types
GraphQL — Inline Fragments
union SearchResult = User | Post | Comment
query Search($term: String!) {
search(term: $term) {
# Common field on all types
__typename
# Type-specific fields using inline fragments
... on User {
name
email
}
... on Post {
title
author { name }
}
... on Comment {
text
post { title }
}
}
}
4 Code Challenge
Challenge: Write a paginated query with variables:
$page: Int = 1, $limit: Int = 10, $filter: PostFilter, and $orderBy: PostOrderBy. Include a @deprecated directive on an old field and use @skip to conditionally include author details.