In this tutorial, we are going to learn how to create a GraphQL schema. A GraphQL schema defines your data model and the operations that can be performed on your data.
At the end of this tutorial, you will understand:
- What a GraphQL schema is
- How to define types in a schema
- How to define relationships between types
- How to define operations that can be performed on the data
A GraphQL schema is at the core of any GraphQL server. It describes the functionality available to the clients which connect to it. The schema is written using the GraphQL Schema Definition Language (SDL).
In GraphQL, the data you can query is organized into types. The most basic components of a GraphQL schema are object types, which just represent a kind of object you can fetch from your service, and what fields it has.
For instance, let's create a Person
type:
type Person {
id: ID!
name: String!
age: Int!
}
Here, we've defined a Person
object type with id
, name
, and age
fields. The ID
, String
, and Int
are built-in scalar types in GraphQL.
We can also define relationships using types. Let's say, each Person
object is associated with a Book
object:
type Book {
title: String!
author: Person!
}
In GraphQL, we define operations using Query
and Mutation
types. The Query
type is used for fetching data while the Mutation
type is used for modifying data.
type Query {
getPerson(id: ID!): Person
}
type Mutation {
addPerson(name: String!, age: Int!): Person
}
Let's define a schema with Person
and Book
types and some operations.
type Person {
id: ID!
name: String!
age: Int!
books: [Book!]
}
type Book {
title: String!
author: Person!
}
type Query {
getPerson(id: ID!): Person
getBook(title: String!): Book
}
type Mutation {
addPerson(name: String!, age: Int!): Person
addBook(title: String!, author: ID!): Book
}
In this schema, a Person
has many Book
objects and a Book
has an Author
who is a Person
. The operations allow us to fetch a Person
or a Book
by their id or title, and to add a Person
or a Book
.
We've learned how to create a GraphQL schema by defining types, relationships, and operations.
You can practice by creating more complex schemas and operations. Try to create a schema for a blog application, for example, with User
, Post
, Comment
types, and corresponding operations.
Exercise: Create a GraphQL schema for a ToDo application. The application should have User
and ToDo
types. A User
can have multiple ToDo
items. Define necessary fields and operations.
Exercise: Modify the above schema to add a completed
field to ToDo
type and add mutations to mark a ToDo
as completed.
Exercise: Create a GraphQL schema for a blog application where a User
can have multiple Post
objects and a Post
can have multiple Comment
objects.