Rails GraphQL Beginner Tutorial - Part 1

rails-graphql-tutorial

Goal

This article is the first post of rails GraphQL beginner serial, I'm going to create a demo to show how to use GraphQL in Rails by querying book records in DB.

First of all, let's list all the thing we need to know about the following steps.

  • The graphql gem.

  • A table named books.

    ID NAME PRICE CREATED_AT UPDATED_AT
    1 Where the Wild Things Are 18.95 2019-06-10 19:41:28 2019-06-10 19:41:28
  • A GraphQL query for fetching book by id.

{
  book(id: 1) {
    id
    name
    price
  }
}

Then, let's explore the steps of how GraphQL is working as.

Initialization

Create a New Project

rails new graphql-tutorial

Update Gemfile

Add the graphql gem in the file named Gemfile at project root directory.

gem 'graphql'

Remove the following lines since we are only going to test API without CSS or JS files, or the Node.js is required by webpacker.

gem 'sass-rails', '~> 5'
gem 'webpacker', '~> 4.0'

Install graphql gem in Rails

Run the following commands to install graphql gem in Rails.

bundle install
rails generate graphql:install

Here is the output, you can see the directory of graphql is created by this command, also routes got updated.

rails graphql installation

A graphql interface is added to routes and another one is GraphiQL which only available in develop environment for debug purpose.

File content in routes.rb

Rails.application.routes.draw do
  if Rails.env.development?
    mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
  end
  post "/graphql", to: "graphql#execute"
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

Mock data

Generate a model

rails g model book

book model creation

Paste the following code to db/migrate/20190610102537_create_books.rb.

class CreateBooks < ActiveRecord::Migration[6.0]
  def change
    create_table :books do |t|
      t.string :name, unique: true, null: false
      t.decimal :price, precision: 10, scale: 2, default: 0.0, null: false
      t.timestamps
    end
  end
end

Migrate table schema

rails db:migrate

rails db migration

Mock a book record in Rails Console

Book.create name: 'Where the Wild Things Are', price: '18.95'

mock-book-data

Pull up the server

rails s
#http://localhost:3000/graphiql

request-graphql-server

It works well if you open the same page as what I have.

Link Book Model to GraphQL Interface

Add schema and queries for GraphQL

To link data in DB with GraphQL, we need to create a book_type.rb file and a book_query.rb file.

book_type.rb

module Types
  class BookType < Types::BaseObject
    description 'The book type of this schema'

    field :id, ID, null: false
    field :name, String, null: false
    field :price, String, null: false
  end
end

Before we create book query, we create a base query first.

base_query.rb

module Queries
  class BaseQuery < GraphQL::Schema::Resolver
  end
end

book_query.rb

module Queries
  class BookQuery < BaseQuery
    type Types::BookType, null: true
    description 'Find a book by id'

    argument :id, Integer, required: true

    def resolve(id:)
      Book.find_by(id: id)
    end
  end
end

Add the new book query to query_type.rb

query_type.rb

module Types
  class QueryType < Types::BaseObject
    field :book, resolver: Queries::BookQuery
  end
end

The files you changed and created should be the same as below.

graphql-query-files

Query Graphql Server

Query Graphql in Browser

Paste the query string to your GraphiQL web client and query.

query-on-graphql-api

Finally, we come to a successful end. This is the beginning article to show you how to integrate GraphQL in Rails, so I keep it as simple as I can and we have not seen the difference and advantage of GraphQL. I'll talk more in following posts.