Schema Definition Language (SDL)
The Schema Definition Language (SDL) is how you define the shape of your GraphQL API. It is the contract between client and server — describing every type, field, and operation available. All GraphQL servers start with a schema.
1 Defining Object Types
GraphQL SDL — Type Definitions
# Object Type — the building block of GraphQL schemas
type User {
id: ID! # ID scalar, non-null (! = required)
name: String! # Non-null string
email: String! # Non-null string
age: Int # Nullable integer
isActive: Boolean! # Non-null boolean
role: Role! # Enum type
posts: [Post!]! # Non-null list of non-null Posts
createdAt: String!
}
type Post {
id: ID!
title: String!
body: String!
author: User!
tags: [String!]
comments: [Comment!]!
}
type Comment {
id: ID!
text: String!
author: User!
post: Post!
}
enum Role {
USER
EDITOR
ADMIN
}
2 Root Operation Types
GraphQL SDL — Query, Mutation, Subscription
# Every schema has up to 3 root types
type Query {
# Read operations
user(id: ID!): User
users(role: Role, limit: Int, offset: Int): [User!]!
post(id: ID!): Post
posts(authorId: ID): [Post!]!
me: User # Current authenticated user
}
type Mutation {
# Write operations
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): Boolean!
createPost(input: CreatePostInput!): Post!
addComment(postId: ID!, text: String!): Comment!
}
type Subscription {
# Real-time events
commentAdded(postId: ID!): Comment!
userOnline: User!
}
# Input types (used for mutations)
input CreateUserInput {
name: String!
email: String!
password: String!
role: Role
}
input UpdateUserInput {
name: String
email: String
}
3 Nullability Rules
| Type Syntax | Meaning | Example Value |
|---|---|---|
String | Nullable string | "hello" or null |
String! | Non-null string | "hello" (never null) |
[String] | Nullable list of nullable strings | ["a", null] or null |
[String!] | Nullable list of non-null strings | ["a", "b"] or null |
[String!]! | Non-null list of non-null strings | ["a", "b"] (never null) |
4 Code Challenge
Challenge: Design a GraphQL schema for an e-commerce platform. Define types for
Product, Order, OrderItem, and Customer. Add appropriate queries to list/get products and orders, and mutations to place an order and update product stock.