⚠ New Class-Based API ⚠

This describes a new API in v1.8.0. Check the upgrade notes for more info.


Scalars are “leaf” values in GraphQL. There are several built-in scalars, and you can define custom scalars, too. (Enums are also leaf values.) The built-in scalars are:

Fields can return built-in scalars by referencing them by name:

# String field:
field :name, String,
# Integer field:
field :top_score, Int, null: false
# or:
field :top_score, Integer, null: false
# Float field
field :avg_points_per_game, Float, null: false
# Boolean field
field :is_top_ranked, Boolean, null: false
# ID field
field :id, ID, null: false

Custom scalars (see below) can also be used by name:

# `homepage: Url`
field :homepage, Types::Url, null: true

In the Schema Definition Language (SDL), scalars are simply named:

scalar DateTime

Custom Scalars

You can implement your own scalars by extending GraphQL::Schema::Scalar. For example:

# app/graphql/types/base_scalar.rb
# Make a base class:
class Types::BaseScalar < GraphQL::Schema::Scalar

# app/graphql/types/url.rb
class Types::Url < Types::BaseScalar
  description "A valid URL, transported as a string"

  def self.coerce_input(input_value, context)
    # Parse the incoming object into a `URI`
    url = URI.parse(input_value)
    if url.is_a?(URI::HTTP) || url.is_a?(URI::HTTPS)
      # It's valid, return the URI object
      raise GraphQL::CoercionError, "#{input_value.inspect} is not a valid URL"

  def self.coerce_result(ruby_value, context)
    # It's transported as a string, so stringify it

Your class must define two class methods:

When incoming data is incorrect, the method may raise GraphQL::CoercionError, which will be returned to the client in the "errors" key.

Scalar classes are never initialized; only their .coerce_* methods are called at runtime.