Schema & Object Types
The schema is the heart of every GraphQL API. It is a typed description of everything clients can ask for and every value they can get back. Because it is strict and machine-readable, the engine can validate queries, tools can autocomplete them, and clients can generate typed code from it.
Object types and fields
Most of a schema is object types: named types with fields. Each field has a type, and that type can be another object type. This is how a schema describes a graph of connected data:
type Library {
name: String!
books: [Book!]!
}
type Book {
title: String!
author: Author!
library: Library
}
type Author {
name: String!
books: [Book!]!
}Book.author points to Author, and Author.books points back to Book. Cycles like this are normal and useful: clients can navigate in either direction, as deep as they need.
Root operation types
Three special object types are the entry points:
| Root type | Holds | Required? |
|---|---|---|
Query |
read fields | yes |
Mutation |
write fields | no |
Subscription |
event streams | no |
If they use these default names, buildSchema finds them automatically. Otherwise a schema block maps operation types to your own names:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
schema {
query: RootQuery
}
type RootQuery {
ping: String
}
`);
console.log(schema.getQueryType().name);
console.log(schema.getMutationType());
const result = await graphql({ schema, source: '{ ping }', rootValue: { ping: 'pong' } });
console.log(JSON.stringify(result.data));RootQuery
undefined
{"ping":"pong"}
Navigating a graph
Let's model authors and books, with relationships stored as ids like they'd be in a database. Field methods on the objects turn ids into objects:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Author { name: String!, books: [Book!]! }
type Book { title: String!, author: Author! }
type Query { book(title: String!): Book }
`);
const authorRows = [{ id: 1, name: 'Octavia E. Butler' }];
const bookRows = [
{ title: 'Kindred', authorId: 1 },
{ title: 'Parable of the Sower', authorId: 1 },
];
const toAuthor = (row) => ({
name: row.name,
books: () => bookRows.filter((b) => b.authorId === row.id).map(toBook),
});
const toBook = (row) => ({
title: row.title,
author: () => toAuthor(authorRows.find((a) => a.id === row.authorId)),
});
const rootValue = {
book: ({ title }) => toBook(bookRows.find((b) => b.title === title)),
};
const query = `{
book(title: "Kindred") {
title
author {
name
books { title }
}
}
}`;
const result = await graphql({ schema, source: query, rootValue });
console.log(JSON.stringify(result.data, null, 2));{
"book": {
"title": "Kindred",
"author": {
"name": "Octavia E. Butler",
"books": [
{
"title": "Kindred"
},
{
"title": "Parable of the Sower"
}
]
}
}
}
We went book → author → that author's books in one query. Because each relationship is a function, only the parts the query visits are loaded.
Descriptions
Strings placed before a type, field or argument are descriptions. They are part of the schema: documentation tools like GraphiQL show them, and introspection returns them. Use "…" for one line and """…""" for multi-line text:
import { buildSchema } from 'graphql';
const schema = buildSchema(`
"""
A book in the catalogue.
"""
type Book {
"The title as printed on the cover."
title: String!
"Number of pages, if known."
pages: Int
}
type Query { books: [Book!]! }
`);
const bookType = schema.getType('Book');
console.log(bookType.description);
for (const field of Object.values(bookType.getFields())) {
console.log(`${field.name}: ${field.type} - ${field.description}`);
}A book in the catalogue.
title: String! - The title as printed on the cover.
pages: Int - Number of pages, if known.
The type system at a glance
| Kind | Keyword | Example | Lesson |
|---|---|---|---|
| Object | type |
type Book { title: String } |
this one |
| Scalar | scalar / built-in |
Int, String, scalar Date |
Scalar Types, Custom Scalars |
| List / Non-null | [ ] / ! |
[Book!]! |
Lists & Non-Null |
| Enum | enum |
enum Genre { SCIFI DRAMA } |
Enums |
| Interface | interface |
interface Node { id: ID! } |
Interfaces |
| Union | union |
union Result = Book | Author |
Unions |
| Input object | input |
input BookInput { title: String! } |
Input Types |
Tip: Design the schema around what clients need, not around your database tables. The schema is a public contract that's hard to change later; your storage can change freely behind it.
Test yourself
Which root type must every schema have?
- Mutation
- Subscription
- Query
- Schema
Is it allowed for Book.author to return Author while Author.books returns [Book]?
- No, cycles are forbidden
- Yes, cycles are normal in a graph schema
- Only with interfaces
- Only in mutations
What is a string written just before a field in SDL?
- A comment that is discarded
- A default value
- A description that is part of the schema
- A directive