Skip to the workspace
Pebellslearn by building
GraphQL Queries  ›  Capstone Project

Directives

Directives 12 minDirectives such as @include and @skip attach to fields or fragments and, usually driven by a Boolean variable, decide whether that part of the query runs, while schema directives such as @deprecated describe the API itself.

graphql / Directives

Explore each scene at your own pace.

01 · The rule

The rule

Directives

The book page has a "Show reviews" toggle. When it is off, fetching reviews is wasted work. You could keep two nearly identical queries, one with reviews and one without, but a directive lets one query switch its own parts on and off.

The rule

@include keeps when true; @skip drops when true.

A directive is an @name with optional arguments, attached to part of a document to change how it is handled. Every GraphQL server supports two in queries:

  • @include(if: Boolean!): the field or fragment is kept only when if is true.
  • @skip(if: Boolean!): the field or fragment is dropped when if is true.

They are almost always fed by a variable:

query BookPage($id: ID!, $withReviews: Boolean!) {
  book(id: $id) {
    title
    price
    reviews(first: 5) @include(if: $withReviews) {
      rating
      text
    }
  }
}
{ "id": "b1", "withReviews": false }

With withReviews false, the server never runs the reviews resolver, and the response has no reviews key at all: not null, not an empty list, simply absent.

Directives can sit on a field, a fragment spread or an inline fragment:

...ReviewLine @skip(if: $compact)

If a field carries both, it is kept only when @skip is false and @include is true.

Directives also appear in schemas, where they describe the API rather than a request. The best-known is @deprecated:

type Book {
  isbn: String @deprecated(reason: "Use isbn13.")
  isbn13: String
}

Servers and tools can define their own directives too, but @include, @skip and @deprecated are the ones every GraphQL user meets.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.