You are viewing the preview version of this book
Click here for the full version.

Schema

The schema is the central document defining a GraphQL API. It is a mandatory part, which means you can be sure it is present for every deployment.

The schema defines types and fields. For example, a simple User object with a username and an email can be defined:

type User {
  username: String!
  email: String
}

Fields can reference other types too. For example, Users can belong to a Group:

type Group {
  name: String!
}

type User {
  username: String!
  email: String
  group: Group
}

With just these two things, you can define complex structures that can model to all sorts of use-cases.

Thinking in graphs

The schema defines the structure of the graph of objects. In the above example, Users have a link to a Group, but that only means the client can move from a specific User object to its corresponding Group object.

Apart from types defined in the schema, fields can be scalar too. Some are defined by GraphQL so they are guaranteed to be available in every implementation:

  • String
  • Int
  • Float
  • Boolean
  • ID

ID is a String, it's just not meant to be used for anything other than identifying things.

Query, Mutation, and Subscription

(Official docs)

There are three special types in GraphQL: Query, Mutation, and Subscription.

Query

The Query defines the entry points for a client query. Think about it like REST endpoints that users can call with some parameters and they return some data. The idea here is the same, but instead of returning a fixed structure, a Query provides the first object(s) in the graph.

For example, a query that returns a user by its username:

# schema
type Query {
  user(username: String!): User
}

This gets a username, which is a String (and it's required, as we'll soon see) and returns a User. Then the client can specify what parts of the User it needs by specifying the result fields. And this can span through multiple objects, traversing the graph.

This client query asks for a specific user, its fields, then its group:

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions