Skip to main content
Version: v2.x

Use Variables / Aliases / Fragments / Directives in Queries

Using variables

In order to make a query re-usable, it can be made dynamic by using variables.

Example: Fetch an author by their author_id:

GraphiQL
Query Variables
Request Headers
Documentation Explorer
No Schema Available

Using aliases

Aliases can be used to return objects with a different name than their field name. This is especially useful while fetching the same type of objects with different arguments in the same query.

Example: First, fetch all articles. Second, fetch the two top-rated articles. Third, fetch the worst-rated article:

GraphiQL
Query Variables
Request Headers
Documentation Explorer
No Schema Available

Using fragments

Sometimes, queries can get long and confusing. A fragment is a set of fields with any chosen name. This fragment can then be used to represent the defined set.

Example: Creating a fragment for a set of article fields (id and title) and using it in a query:

GraphiQL
Query Variables
Request Headers
Documentation Explorer
No Schema Available

Using directives

Directives make it possible to include or skip a field based on a boolean expression passed as a query variable.

@include(if: Boolean)

With @include(if: Boolean), it is possible to include a field in the query result based on a Boolean expression.

Example: The query result includes the field publisher, as $with_publisher is set to true:

GraphiQL
Query Variables
Request Headers
Documentation Explorer
No Schema Available

Example: The query result doesn't include the field publisher, as $with_publisher is set to false:

GraphiQL
Query Variables
Request Headers
Documentation Explorer
No Schema Available

@skip(if: Boolean)

With @skip(if: Boolean), it is possible to exclude (skip) a field in the query result based on a Boolean expression.

Example: The query result doesn't include the field publisher, as $with_publisher is set to true:

GraphiQL
Query Variables
Request Headers
Documentation Explorer
No Schema Available

Example: The query result includes the field publisher, as $with_publisher is set to false:

GraphiQL
Query Variables
Request Headers
Documentation Explorer
No Schema Available