Yair Nevet
Yair Nevet

Reputation: 13013

`schema` keyword usage in GraphQL SDL

I'm trying to understand the meaning and usage of the schema keyword on a GraphQL schema definition (SDL).

Let's take the following schema definition, for example:

# Enumeration type for a level of priority
enum Priority {
  LOW
  MEDIUM
  HIGH
}

# Our main todo type
type Todo {
  id: ID!
  name: String!
  description: String
  priority: Priority!
}

type Query {
  # Get one todo item
  todo(id: ID!): Todo
  # Get all todo items
  allTodos: [Todo!]!
}

type Mutation {
  addTodo(name: String!, priority: Priority = LOW): Todo!
  removeTodo(id: ID!): Todo!
}

schema {
  query: Query
  mutation: Mutation
}

Can someone please explain to me the meaning of the schema keyword/block in the definition above, why do we anyway need it?

schema {
  query: Query
  mutation: Mutation
}

Upvotes: 3

Views: 431

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84857

There are three types of operations in GraphQL:

  • query – a read‐only fetch.
  • mutation – a write followed by a fetch.
  • subscription – a long‐lived request that fetches data in response to source events.

In order for your schema to support a particular operation, it must associate a particular object type with it. Each type serves as the root or entry point to the rest of your schema. This is what this SDL does -- it shows the root operation type associated with each operation in the schema. Only the query type is required -- the other two are optional and can be omitted from the definition. Each root operation type must be an object type -- it cannot be a scalar, enum, etc.

Note that by convention the three types are named Query, Mutation and Subscription -- but they could be named just about anything. For example, you could have a schema like this:

schema {
  query: Dog
}

type Dog {
  breeds: [Breed!]!
}

The name of the type is, for the most part, inconsequential. However, if you follow the standard convention (Query, Mutation and Subscription), the schema definition can be omitted altogether. GraphQL will just assume that the Query type is the query root type and so on.

Upvotes: 5

Related Questions