📄 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 backend 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: Intmissions: [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:
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 GraphOS 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 descriptionwith a line break"""
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!
Share your questions and comments about this lesson
Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.
You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.