Schemas and the Type System
🎯 Introduction
In the previous article, we saw that a GraphQL service validates queries against its schema and reports unknown fields immediately. The schema is the foundation of a GraphQL service: it describes the server's data and guides clients as they write queries.
By the end of this article, you will be comfortable with the five built-in scalar types, non-null and list modifiers, enums, and custom types that describe relationships. You will be able to write a clear schema that also serves as documentation.
🧱 What Is a Schema?
A schema is a data contract written in GraphQL. It tells clients what data is available, the name and type of each field, and whether it can be null.
In Apollo Server, the schema is the typeDefs string:
const typeDefs = `#graphql
type User {
id: ID!
username: String!
age: Int
}
type Query {
users: [User!]!
}
`;
Think of it as a menu: customers can order the dishes listed, but anything else is unavailable. type User defines a data structure, while type Query defines the entry points clients can query.
Because the schema has a strongly typed, defined structure, tools can read it to generate documentation and code suggestions. This is why GraphQL is often described as self-documenting.
🧱 Scalar Types
Scalars are the smallest units in the type system and have no subfields. GraphQL includes five built-in scalars:
| Type | Meaning | Example |
|---|---|---|
Int | Signed 32-bit integer | 20 |
Float | Double-precision floating-point number | 99.5 |
String | UTF-8 string | "Alex" |
Boolean | Boolean value | true / false |
ID | Unique identifier | "1" |
The first four correspond to familiar JavaScript concepts. ID deserves a closer look: it is represented as a string but semantically identifies a unique entity, usually a primary key. Use ID rather than String for identifier fields to express that intent.
Int is a 32-bit integer, with a range of roughly ±2.1 billion. Represent values that may exceed this range, such as phone numbers and millisecond timestamps, with String to avoid overflow.✨ Non-Null Types and Lists
A field's underlying type is only part of the picture. You also need to specify whether it can be null and whether it contains one value or a collection. GraphQL provides two modifiers:
- Exclamation mark
!: marks a type as non-null, so the field cannot returnnull. - Square brackets
[]: indicate a list, represented as an array.
These can be combined. A type such as [User!]! becomes easier to understand when broken down:
type Query {
users: [User!]!
}
users is a list of non-null User values, and the list itself is non-null. It may return an empty array [], but cannot return null.
Here are the common combinations:
| Type | Can the list be null? | Can list items be null? |
|---|---|---|
[User] | Yes | Yes |
[User]! | No | Yes |
[User!] | Yes | No |
[User!]! | No | No |
[User!]! is a common choice for list fields. It provides the strictest guarantees and lets clients use the list without checking it or its items for null.
🛠 Custom Types and Relationships
Data in real projects is usually connected: users publish articles, and each article belongs to a user. GraphQL represents these relationships through custom types that reference each other:
type Article {
id: ID!
title: String!
author: User!
}
type User {
id: ID!
username: String!
articles: [Article!]!
}
There are two key points:
Article.authorhas the custom typeUser, meaning that an article's author is a user.User.articleshas the type[Article!]!, meaning that a user has a list of articles.
Once these relationships are defined, clients can retrieve nested data in a single query, selecting the levels they need:
{
users {
username
articles {
title
}
}
}
💡 Enums and Descriptions
Some fields accept only a fixed set of values, such as administrator and regular user roles. An enum expresses this more precisely than String:
enum Role {
ADMIN
USER
}
type User {
id: ID!
username: String!
role: Role!
}
Enum values conventionally use uppercase names with underscores. Values outside this set fail validation when supplied by a client or returned for the field, preventing invalid values from being accepted.
You can also use """ to add descriptions to types and fields. These appear in Apollo Sandbox's documentation panel:
"""A user in the system"""
type User {
"""The user's unique identifier"""
id: ID!
"""Display name; does not need to be unique"""
username: String!
}
A few seconds spent documenting key fields will help your teammates, and your future self, understand the schema.
❓ Questions and Answers
Q1: How does ID differ from String?
Both are represented as strings, but their meaning differs. ID identifies an entity rather than text intended for display. Tools and developers recognize it as an identifier or primary key, while String represents ordinary text.
Q2: Why can't Int store a millisecond timestamp?
A millisecond timestamp such as 1753000000000 exceeds the 32-bit integer limit of roughly 2.1 billion and fails validation. Use String for large values like these.
Q3: How do [User!]! and [User] differ in their responses?
The former guarantees an array, populated or empty, that clients can use directly. The latter may be null and may contain null items, requiring repeated null checks that are easy to miss.
Q4: Can enum values use Chinese characters?
Use uppercase English names with underscores. Enum values appear directly in queries, and GraphQL names do not allow Chinese characters. Handle localized display labels in the frontend.
Q5: What happens if typeDefs contains an error?
The service reports the error and its location at startup, for example for undefined types or unmatched braces. Schema syntax errors surface before the service starts handling requests.
🧪 Exercises
Exercise 1: Design an Article type with an ID, title, publication time (consider which type to use), and author. Define its relationship with User.
# Write your code here
Exercise 2: Add a user status field with an enum containing only enabled and disabled values. Also make the role field non-null.
# Write your code here
🎉 You now know the common building blocks of GraphQL's type system! Next, we will return to queries and learn how arguments, variables, and nested queries let clients use the schema.
