How GraphQL Types Work
Learn how GraphQL is made up of types, and how they come together to make up the GraphQL schema.
We'll cover the following
Introducing types
No matter what implementation of GraphQL you use, the way its API is expressed is via the types that make up the schema
, which is the blueprint that makes up a GraphQL API.
A GraphQL schema is nearly always written in Schema Definition Language (SDL). As noted in the GraphQL Documentation, this is a way of representing the structure of your API without worrying about language-specific syntax.
To write your schema, you need to understand the types that make up a schema.
Types vs fields
The majority of entities in a GraphQL schema are made up of types
and fields
. These are fairly straightforward to understand:
A type is a thing. On its own, it’s not that interesting. We are more interested in their contents, which are represented by fields.
Consider this example:
type User {
id: String!
email: String!
name: String
}
Here we can see the type User
. That User
type contains several fields. Namely, id
, email
, and name
.
Most of this is quite easy to read and understand. But what about the !
after String
? This means that the field is non-nullable. GraphQL is saying that it will always return a value when you query this field.
As for String
iitself? This was not created by you. Instead, this is a scalar
. GraphQL has a number of built-in scalars that represent a concrete data type. Some of the scalars in GraphQL are:
String
Int
Boolean
The great thing about fields is that, instead of only scalars, they can also return types. This allows you to write the powerful nested queries that you may have seen before. Like this:
query {
listUsers {
id
email
name
photos {
url
}
}
}
In this example, you can see that we are running a query called listUsers
, which then provides several fields
for the User
type.
We can also access the user’s photos by providing it as a field. GraphQL is intelligent enough to understand the relationships between types when they are specified in the schema.
For reference, a user might be structured like this in the GraphQL schema:
type Query {
listUsers: [User] # Return a list of users
}
type User {
id: String!
email: String!
name: String
photos: [Image] # Return items contained in the `Image` type.
}
type Image {
url: String!
}
Recap
So as you can see, it is fairly straightforward to get started writing a schema. With that said, writing a robust and scalable schema is much harder. This is something we will discuss later on.
For now, it’s worth remembering:
- A GraphQL schema is made up of types and fields
- A field can refer to a type like in our
photos
field in the example above - A field can be one of the built-in scalars, a custom scalar, or a type
!
denotes a non-nullable field[]
means that an array will be returned
Congratulations! You can now read the basics of a schema in GraphQL.
Get hands-on with 1200+ tech skills courses.