In this tutorial, we will focus on creating a GraphQL schema using the Schema Definition Language (SDL). You'll learn the fundamentals of a GraphQL schema, how to structure it using SDL and gain a practical understanding of how to build schemas for your GraphQL servers.
By the end of this tutorial, you should be able to:
To successfully follow along with this tutorial, you should have:
A GraphQL schema is a contract between the client and the server. It defines the types of data a client can request from the server.
GraphQL SDL (Schema Definition Language) is a language-agnostic way to describe the schema of your GraphQL server. It is human-readable and easy to understand, making it the preferred way to define schemas.
Here is how you can define a basic schema in SDL:
type Tweet {
id: ID!
body: String!
date: String!
}
In the above example, Tweet
is an object type with fields id
, body
, and date
. Each field has a type, and !
indicates that the field is non-nullable.
type Author {
id: ID!
name: String!
tweets: [Tweet!]!
}
In this example, we define a new object type Author
. We've also created a relationship between Author
and Tweet
types using an array. This means that an author can have multiple tweets.
type Query {
getTweet(id: ID!): Tweet
getAuthor(id: ID!): Author
}
The Query
type is a special type that lets us query data. Here, we've defined two queries getTweet
and getAuthor
that retrieve a single tweet and author respectively based on their id
.
In this tutorial, we've covered the basics of creating a GraphQL schema using SDL. We've learned about object types, fields, and query types.
Your next steps should be learning about mutation and subscription types, which allow you to change data and subscribe to data changes respectively.
For additional resources, consider:
Create a schema for a blog post and comments. A blog post should have a title, body, and author, and a comment should have a body and author.
Create a query type that retrieves a blog post based on its ID.
Create a query type that retrieves all comments for a blog post based on the post's ID.
# Solutions
# Exercise 1
type BlogPost {
id: ID!
title: String!
body: String!
author: Author!
}
type Comment {
id: ID!
body: String!
author: Author!
}
# Exercise 2
type Query {
getBlogPost(id: ID!): BlogPost
}
# Exercise 3
type Query {
getComments(postId: ID!): [Comment!]!
}
For further practice, try creating schemas for different types of applications, such as a shopping cart, a todo list, etc.