Built-in Directives in GraphQL: What They Are and How to Use Them
@include, @skip, and @deprecated, which control whether fields are included or skipped and mark schema elements as outdated.How It Works
Think of built-in directives in GraphQL as traffic signals for your queries and schemas. They tell the GraphQL engine when to stop, go, or take a detour. For example, @include and @skip act like conditional gates that decide if a part of your query should run based on a condition you provide.
When you run a query, these directives check the conditions and either include or exclude certain fields dynamically. The @deprecated directive works like a warning sign in your schema, telling users that a field or enum value should no longer be used, helping teams manage changes smoothly.
Example
This example shows how to use @include and @skip directives to control which fields appear in the query result based on a variable.
query GetUser($showEmail: Boolean!) {
user {
name
email @include(if: $showEmail)
phone @skip(if: $showEmail)
}
}When to Use
Use @include and @skip when you want to fetch different data based on user input or app state without writing multiple queries. For example, show an email only if the user has permission.
Use @deprecated in your schema to mark fields or enum values that should be avoided because they will be removed or replaced. This helps developers know which parts of the API are outdated and plan updates accordingly.
Key Points
- @include(if: Boolean) includes a field only if the condition is true.
- @skip(if: Boolean) skips a field if the condition is true.
- @deprecated(reason: String) marks schema elements as outdated with an optional explanation.
- Built-in directives help make queries flexible and schemas maintainable.