0
0
GraphqlConceptBeginner · 3 min read

Built-in Directives in GraphQL: What They Are and How to Use Them

Built-in directives in GraphQL are special instructions that modify the execution or validation of queries and schemas. The main built-in directives are @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.

graphql
query GetUser($showEmail: Boolean!) {
  user {
    name
    email @include(if: $showEmail)
    phone @skip(if: $showEmail)
  }
}
Output
{ "data": { "user": { "name": "Alice", "email": "alice@example.com" } } }
🎯

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.

Key Takeaways

Built-in directives control query execution and schema behavior dynamically.
@include and @skip let you conditionally fetch fields based on variables.
@deprecated warns users about outdated schema elements to ease transitions.
Using directives improves API flexibility and communication with clients.