GraphQL - 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:
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:
email, which may return aStringornil.handle, which returns aStringbut nevernil(!means the field never returnsnil)friends, which returns a list of otherUsers ([...]means the field returns a list of values;User!means the list containsUserobjects, and never containsnil.)
The same object can be defined using Ruby:
class Types::User < GraphQL::Schema::Object
field :email, String
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
comment "Comment of the TodoList type"
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::Types::Relay::Node
implements Types::UserAssignableType
When an object implements interfaces, it:
- inherits the GraphQL field definitions from that object
- includes that module into the object definition
Read more about interfaces in the Interfaces guide