Understanding Object Types and Fields

Tutorial 2 of 5

Understanding Object Types and Fields in GraphQL

1. Introduction

Goal of the Tutorial

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.

Learning Outcomes

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

Prerequisites

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.

2. Step-by-Step Guide

Object Types

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

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.

3. Code Examples

Defining Object Types and Fields

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.

Querying Fields

{
  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.

4. Summary

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.

5. Practice Exercises

  1. Define an object type for a Movie with fields: title, director, and releaseYear. What would a query look like to fetch all three fields?

  2. 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.

Solutions

  1. Object type and query for Movie
type Movie {
  title: String
  director: String
  releaseYear: Int
}

{
  movie {
    title
    director
    releaseYear
  }
}
  1. Modified User object type and query
type User {
  id: ID
  name: String
  email: String
  age: Int
}

{
  user {
    name
    age
  }
}