3. Schema definition language (SDL)
3m

📄 The GraphQL schema

A schema is like a contract between the server and the client. It defines what a GraphQL API can and can't do, and how clients can request or change data. It's an abstraction layer that provides flexibility to consumers while hiding back-end implementation details.

Before we jump into defining our schema, let's run through a quick crash course on GraphQL's Schema Definition Language, or SDL.

If you're already familiar with SDL, feel free to move to the next lesson.

At its heart, a schema is a collection of object types that contain fields. Each field has a type of its own. A field's type can be scalar (such as an Int or a String), or it can be another object type. For example, the Track object type in our schema will have an author field of type Author.

We declare a type using the type keyword, followed by the name of the type (PascalCase is best practice), then opening brackets to hold its contained fields:

type SpaceCat {
# Fields go here
}

Fields are declared by their name (camelCase), a colon, and then the type of the field (scalar or object). A field can also contain a list, indicated by square brackets:

type SpaceCat {
age: Int
missions: [Mission]
}

Unlike Javascript objects (which look very similar), fields are not separated by commas. In addition, we can indicate whether each field value is nullable or non-nullable. If a field should never be null, we add an exclamation mark after its type:

types and fields

Which of the following are valid field types?

Code Challenge!

Define a 'SpaceCat' type with the following fields: 'name' of type String (non null), 'age' of type Int, and 'missions' of type List of 'Mission'

All right, last thing before we start writing our schema: descriptions.

It's good practice to document your schema, in the same way that it's helpful to comment your code. It makes it easier for your teammates (and future you) to make sense of what's going on. It also allows tools like the Apollo Studio Explorer to guide API consumers on what they can achieve with your API right when and where they need it.

To do that, the SDL lets you add descriptions to both types and fields by writing strings (in quotation marks) directly above them.

"I'm a regular description"

Triple "double quotes" allow you to add line breaks for clearer formatting of lengthier comments.

"""
I'm a block description
with a line break
"""
type definitions comment

Code Challenge!

Add a block description for the SpaceCat type (triple "double quotes") and a normal description for the name field

With that final point covered, we're done with our quick refresher. Let's build our schema!

Previous
Next