The Type System
Every query in this course has leaned on a schema you have only seen in pieces. Now it is time to build it deliberately. The schema is not documentation that might drift from the truth: it is the rulebook the server checks every request against, before a single resolver runs.
The rule
Six named kinds, two wrappers, three roots.
A schema is written in the schema definition language (SDL). Every named type is one of six kinds, and the keyword tells you which:
| Keyword | Kind | Used for |
|---|---|---|
scalar |
Scalar | Single values: Int, String, a custom Date |
enum |
Enum | One of a fixed set of values: FANTASY, MYSTERY |
type |
Object | Output data with fields: Book, Author |
interface |
Interface | Fields that several object types share |
union |
Union | "One of these object types" |
input |
Input object | Structured arguments: AddReviewInput |
Two wrappers modify any type where it is used:
[Book]is a list of books.Book!is non-null: the value can never benull.
Three root types are the entry points. Query is required; Mutation and Subscription are optional:
type Query {
book(id: ID!): Book
books(genre: Genre, first: Int = 10): [Book!]!
}
type Mutation {
addReview(input: AddReviewInput!): Review!
}
type Subscription {
reviewAdded(bookId: ID!): Review!
}Because every field and argument has a known type, the server can validate a request completely before running it: an unknown field, a missing required argument or a string where an Int belongs is rejected with an error, and no resolver is called.
The schema also describes itself. Special introspection fields such as __schema and __type(name: "Book") let tools ask the server which types and fields exist. That is how editors autocomplete queries and how documentation explorers are generated.