Ask a Question

GraphQL Variables

Variables simplify GraphQL queries and mutations by letting you pass data separately. A GraphQL request can be split into two sections: one for the query or mutation, and another for variables.

Variables can be declared after the query or mutation and are passed like arguments to a function and begin with $.

Query Example :

query post($filter: PostFilter) {
	queryPost(filter: $filter) {
		title
		text
		author {
			name
		}
	}
}

Variables:

{
	"filter": {
		"title": {
			"eq": "First Post"
		}
	}
}

Result:

{
	"data": {
		"queryPost": [{
			"title": "First Post",
			"text": "Hello world!",
			"author": [{
				"name": "A.N. Author"
			}]
		}]
	}
}

Mutation Example :

mutation addAuthor($author: AddAuthorInput!) {
	addAuthor(input: [$author]) {
		author {
			name
			posts {
				title
				text
			}
		}
	}
}

Variables:

{
	"author": {
		"name": "A.N. Author",
		"dob": "2000-01-01",
		"posts": [{
			"title": "First Post",
			"text": "Hello world!"
		}]
	}
}

Result:

{
	"data": {
		"addAuthor": {
			"author": [{
				"name": "A.N. Author",
				"posts": [{
					"title": "First Post",
					"text": "Hello world!"
				}]
			}]
		}
	}
}