This tutorial aims to provide a comprehensive understanding of object types and fields, which are integral parts of a GraphQL schema. They are the building blocks for defining and manipulating data in GraphQL.
After completing this tutorial, you'll be able to:
- Understand what object types and fields are in GraphQL
- Define your own object types and fields
- Query and manipulate data using object types and fields
This tutorial assumes that you have a basic understanding of GraphQL. If you're new to GraphQL, you might want to read the official GraphQL documentation before proceeding.
In GraphQL, an object type is a user-defined data type that represents the objects that you can fetch from your service. They are defined in the GraphQL schema and consist of fields.
type User {
id: ID
name: String
email: String
}
In the above example, User
is an object type, and it has three fields: id
, name
, and email
.
Fields are the properties that you can query on an object. They represent the individual pieces of data that can be fetched from the object.
{
user {
name
email
}
}
In this example, name
and email
are fields on the User
object.
type Book {
title: String
author: String
publishedYear: Int
}
In this example, Book
is an object type with three fields: title
, author
, and publishedYear
. The types of these fields are String
and Int
, which are scalar types in GraphQL.
{
book {
title
author
}
}
In this query, we are requesting the title
and author
fields of the Book
object. The server will return a JSON object with these properties.
In this tutorial, we've learned about object types and fields in GraphQL. We've seen how to define our own object types and fields and how to query them. The next step would be to learn about other types in GraphQL, such as Interface and Union types. Check the official GraphQL documentation for more information.
Define an object type for a Movie
with fields: title
, director
, and releaseYear
. What would a query look like to fetch all three fields?
How would you modify the User
object type to include a new field age
of type Int
? Write a query to fetch the name
and age
of a User
.
Movie
type Movie {
title: String
director: String
releaseYear: Int
}
{
movie {
title
director
releaseYear
}
}
User
object type and querytype User {
id: ID
name: String
email: String
age: Int
}
{
user {
name
age
}
}