Objects

GraphQL object types are the bread and butter of GraphQL APIs. Each object has fields which expose data and may be queried by name. For example, we can query a User like this:

user {
  handle
  email
}

And get back values like this:

{
  "user" => {
    "handle" => "rmosolgo",
    "email" => nil,
  }
}

Generally speaking, GraphQL object types correspond to models in your application, like User, Product, or Comment. Sometimes, object types are described using the GraphQL Schema Definition Language (SDL):

type User {
  email: String
  handle: String!
  friends: [User!]!
}

This means that User objects have three fields:

The same object can be defined using Ruby:

class Types::User < GraphQL::Schema::Object
  field :email, String, null: true
  field :handle, String, null: false
  field :friends, [User], null: false
end

The rest of this guide will describe how to define GraphQL object types in Ruby. To learn more about GraphQL object types in general, see the GraphQL docs.

Object classes

Classes extending GraphQL::Schema::Object describe Object types and customize their behavior.

Object fields can be created with the field(...) class method, described in detail below

Field and argument names should be underscored as a convention. They will be converted to camelCase in the underlying GraphQL type and be camelCase in the schema itself.

# first, somewhere, a base class:
class Types::BaseObject < GraphQL::Schema::Object
end

# then...
class Types::TodoList < Types::BaseObject
  description "A list of items which may be completed"

  field :name, String, "The unique name of this list", null: false
  field :is_completed, String, "Completed status depending on all tasks being done.", null: false
  # Related Object:
  field :owner, Types::User, "The creator of this list", null: false
  # List field:
  field :viewers, [Types::User], "Users who can see this list", null: false
  # Connection:
  field :items, Types::TodoItem.connection_type, "Tasks on this list", null: false do
    argument :status, TodoStatus, "Restrict items to this status", required: false
  end
end

Fields

Object fields expose data about that object or connect the object to other objects. You can add fields to your object types with the field(...) class method.

See the Fields guide for details about object fields.

Implementing interfaces

If an object implements any interfaces, they can be added with implements, for example:

# This object implements some interfaces:
implements GraphQL::Relay::Node.interface
implements Types::UserAssignableType

When an object implements interfaces, it:

Read more about interfaces in the Interfaces guide