Conditional query fields
Omit optional fields based on a client-provided Boolean.
GraphQL · Const
A GraphQL directive is an @ annotation that changes how a schema or operation is interpreted. Directives may annotate schema definitions, affect client operations, and are restricted to declared locations.
A GraphQL directive is an annotation beginning with @ that can alter how a schema element or operation is validated or executed. Executable directives can be placed in client operations, while type-system directives annotate schema definitions; each directive declares the locations where it is allowed.
@name(arguments)| Name | Type | Description |
|---|---|---|
if | Boolean | For the built-in executable directives, a Boolean condition named if controls inclusion or skipping. |
Directives do not return a standalone value; they influence validation, schema interpretation, or operation execution.
@ prefix identifies a directive and signals that it may modify a schema or operation.query User($showEmail: Boolean!) {
user(id: "1") {
id
name
email @include(if: $showEmail)
}
}The variable controls whether the email field is included in the response.
Omit optional fields based on a client-provided Boolean.
Mark schema elements for special validation or execution treatment.
Apply reusable application-specific behavior beyond ordinary field arguments.
Directives are @ annotations that can change validation or execution behavior. They can be attached to schema definitions as type-system directives or used in operations as executable directives.
Follow-up: How does a client conditionally omit a field? Use @include(if: Boolean) and provide a Boolean value; use @skip(if: Boolean) when the field should be excluded when the value is true.
The built-in executable directives are @include(if: Boolean) and @skip(if: Boolean). The former includes a field only when its argument is true, while the latter skips it when its argument is true.
Follow-up: Where can these directives be attached? They can be used on fields and fragment inclusion, according to the queries documentation.
A custom directive must be defined with its allowed locations, such as FIELD_DEFINITION or ENUM_VALUE. Its use is then restricted to those declared locations.
Follow-up: Why use a custom directive? It can encode reusable schema annotation or operation behavior when ordinary field arguments are insufficient.
@include@skip@deprecatedFIELD_DEFINITIONENUM_VALUEexecutable directivestype-system directives