▄██████▄ ▄████████ ▄████████ ▄███████▄ ▄█ █▄ ████████▄ ▄█ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ █▀ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▄███ ▄███▄▄▄▄██▀ ███ ███ ███ ███ ▄███▄▄▄▄███▄▄ ███ ███ ███ ▀▀███ ████▄ ▀▀███▀▀▀▀▀ ▀███████████ ▀█████████▀ ▀▀███▀▀▀▀███▀ ███ ███ ███ ███ ███ ▀███████████ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ███ ▀ ███ ███▌ ▄ ████████▀ ███ ███ ███ █▀ ▄████▀ ███ █▀ ▀██████▀▄█ █████▄▄██ ███ ███ ▀

A GraphQL server implementation for Ruby

Welcome

Gem Version

Installation

You can install graphql from RubyGems by adding to your application’s Gemfile:

# Gemfile
gem "graphql"

Then, running bundle install:

$ bundle install

Getting Started

On Rails, you can get started with a few GraphQL generators:

rails g graphql:install
rails g graphql:object Post title:String rating:Int comments:[Comment]

Or, you can build a GraphQL server by hand:

  • Define some types
  • Connect them to a schema
  • Execute queries with your schema

Declare types

Types describe objects in your application and form the basis for GraphQL’s type system.

PostType = GraphQL::ObjectType.define do
  name "Post"
  description "A blog post"
  # `!` marks a field as "non-null"
  field :id, !types.ID
  field :title, !types.String
  field :body, !types.String
  field :comments, types[!CommentType]
end

CommentType = GraphQL::ObjectType.define do
  name "Comment"
  field :id, !types.ID
  field :body, !types.String
  field :created_at, !types.String
end

Build a Schema

Before building a schema, you have to define an entry point to your system, the “query root”:

QueryType = GraphQL::ObjectType.define do
  name "Query"
  description "The query root of this schema"

  field :post do
    type PostType
    argument :id, !types.ID
    description "Find a Post by ID"
    resolve ->(obj, args, ctx) { Post.find(args["id"]) }
  end
end

Then, build a schema with QueryType as the query entry point:

Schema = GraphQL::Schema.define do
  query QueryType
end

This schema is ready to serve GraphQL queries! See “Configuration Options” for all the schema options.

Execute queries

You can execute queries from a query string:

query_string = "
{
  post(id: 1) {
    id
    title
  }
}"
result_hash = Schema.execute(query_string)
# {
#   "data" => {
#     "post" => {
#        "id" => 1,
#        "title" => "GraphQL is nice"
#     }
#   }
# }

See “Executing Queries” for more information about running queries on your schema.

Use with Relay

If you’re building a backend for Relay, you’ll need:

Use with Apollo Client

Apollo Client is a full featured, simple to use GraphQL client with convenient integrations for popular view layers. You don’t need to do anything special to connect Apollo Client to a graphql-ruby server.