mot.la

Getting Started With Rails: Installing GraphQL

In this article, I show you how to implement GraphQL with Ruby on Rails. If you have not already, follow steps here to get setup with Rails, Postgres, and Puma.

Also, you can find this tutorial already wrapped up into a Heroku deployable template here.

Let's begin by creating a model.

bin/rails generate model User email:string
bin/rake db:migrate

This sets up a User model for us. Let's populate it with one record. First enter the console.

bin/rails console

Create the user.

User.create(email: "you@email.com")

Now we're ready to configure GraphQL.

Setup GraphQL

Add the following gems to your Gemfile.

gem 'graphql'
gem 'graphiql-rails'
gem 'graphql-relay'

Run bundle install.

Next setup the graphql controller.

touch app/controllers/graphql_controller.rb

Paste in the following:

class GraphqlController < ApplicationController
  skip_before_filter :verify_authenticity_token

  def query
    variables = params[:variables]
    variables = JSON.parse(variables) if variables && variables.is_a?(String)

    result_hash = Schema.execute(params[:query], variables: variables)
    render json: result_hash
  end
end

Next add the following to your config/routes.rb.

Rails.application.routes.draw do
  ...
  post '/graphql', to: 'graphql#query'
  mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql" if Rails.env.development?
  ...
end

Good, now we can configure our Schema model.

touch app/models/schema.rb

Paste in the following.

UserType = GraphQL::ObjectType.define do
  name 'User'
  description '...'
  
  field :id, !types.String
  field :email, !types.String
end

QueryRoot = GraphQL::ObjectType.define do
  name 'Query'
  description '...'
  
  field :user do
    type UserType
    argument :id, !types.String
    resolve -> (root, args, ctx) {
      User.find(args[:id])
    }
  end
end

Schema = GraphQL::Schema.new(
  query: QueryRoot
)

That's it! You now have a working GraphQL implementation on Rails. Let's try out a GraphQL query.

Run a GraphQL Query

Start up your rails server.

bin/rails server -b 127.0.0.1 -p 3000

Then visit localhost:3000/graphiql

In the left hand pane, paste the following:

{
  user(id:"1") {
    email
  }
}

You should see a result like the following.

{
  "data": {
    "user": {
      "email": "you@email.com"
    }
  }
}

Congratulations! You just ran your very first GraphQL query.