Setting the file. One moment.
Subchapter 10.5
references/variables.mdMarkdown6 KBView on GitHub
This reference covers patterns for using variables in GraphQL operations.
Variables are declared in the operation definition:
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}Variables are referenced with $ prefix:
query GetUser($id: ID!) {
user(id: $id) {
# $id used here
id
name
}
}Variables are passed as a separate JSON object:
const { data } = await client.query({
query: GET_USER,
variables: {
id: "user_123",
},
});query SearchPosts($query: String!, $status: PostStatus, $first: Int!, $after: String) {
searchPosts(query: $query, status: $status, first: $first, after: $after) {
edges {
node {
id
title
}
}
}
}{
"query": "graphql",
"status": "PUBLISHED",
"first": 10,
"after": "cursor_abc"
}query Example(
$id: ID!
$name: String!
$count: Int!
$price: Float!
$active: Boolean!
) {
# ...
}query Example(
$date: DateTime!
$email: Email!
$url: URL!
) {
# ...
}query GetPosts($status: PostStatus!) {
posts(status: $status) {
id
title
}
}{
"status": "PUBLISHED"
}query GetUsers($ids: [ID!]!) {
users(ids: $ids) {
id
name
}
}{
"ids": ["user_1", "user_2", "user_3"]
}mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
}
}{
"input": {
"title": "My Post",
"content": "Post content...",
"tags": ["graphql", "api"]
}
}query Example(
$required: String! # Must be provided, cannot be null
$optional: String # Can be omitted or null
$requiredList: [String!]! # List required, items required
$optionalList: [String] # List optional, items optional
) {
# ...
}query GetPosts($first: Int = 10, $status: PostStatus = PUBLISHED) {
posts(first: $first, status: $status) {
id
title
}
}If not provided, uses defaults:
{}
// Equivalent to: { "first": 10, "status": "PUBLISHED" }Override defaults:
{
"first": 20
}
// Uses first: 20, status: PUBLISHED (default)# Variable is optional (no !) but has default
query GetPosts($first: Int = 10) {
posts(first: $first) {
id
}
}query GetPosts($orderBy: PostOrderInput = { field: CREATED_AT, direction: DESC }) {
posts(orderBy: $orderBy) {
id
title
}
}Use defaults for:
first: Int = 20)direction: SortDirection = DESC)status: Status = ACTIVE)includeArchived: Boolean = false)mutation CreateOrder($input: CreateOrderInput!) {
createOrder(input: $input) {
id
total
}
}{
"input": {
"customer": {
"email": "customer@example.com",
"name": "John Doe"
},
"items": [
{ "productId": "prod_1", "quantity": 2 },
{ "productId": "prod_2", "quantity": 1 }
],
"shippingAddress": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "US"
}
}
}mutation BulkCreateUsers($inputs: [CreateUserInput!]!) {
bulkCreateUsers(inputs: $inputs) {
id
email
}
}{
"inputs": [
{ "email": "user1@example.com", "name": "User 1" },
{ "email": "user2@example.com", "name": "User 2" },
{ "email": "user3@example.com", "name": "User 3" }
]
}query SearchProducts($filter: ProductFilter!) {
products(filter: $filter) {
id
name
price
}
}{
"filter": {
"category": "ELECTRONICS",
"priceRange": {
"min": 100,
"max": 500
},
"inStock": true,
"tags": ["featured", "sale"]
}
}# Good: Uses variable
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
# Bad: Hardcoded value
query GetUser {
user(id: "123") {
id
name
}
}# Good: Clear relationship
query GetUser($userId: ID!) {
user(id: $userId) {
id
}
}
# Also good: Same name
query GetUser($id: ID!) {
user(id: $id) {
id
}
}
# Bad: Confusing names
query GetUser($x: ID!) {
user(id: $x) {
id
}
}# Good
query SearchPosts(
$searchQuery: String!
$authorId: ID
$publishedAfter: DateTime
$maxResults: Int = 20
) {
searchPosts(
query: $searchQuery
author: $authorId
after: $publishedAfter
first: $maxResults
) {
# ...
}
}
# Bad
query SearchPosts($q: String!, $a: ID, $d: DateTime, $n: Int) {
# ...
}// Good: Variables object mirrors input structure
const variables = {
input: {
title: formData.title,
content: formData.content,
tags: formData.tags,
},
};
// Less clear: Flat variables
const variables = {
title: formData.title,
content: formData.content,
tags: formData.tags,
};function createPost(input: CreatePostInput) {
// Validate before sending
if (!input.title?.trim()) {
throw new Error("Title is required");
}
if (input.title.length > 200) {
throw new Error("Title too long");
}
return client.mutate({
mutation: CREATE_POST,
variables: { input },
});
}// Generated types from schema
interface GetUserQueryVariables {
id: string;
}
// Use with Apollo Client
const { data } = useQuery<GetUserQuery, GetUserQueryVariables>(GET_USER, {
variables: { id: userId }, // Type-checked
});