Setting Up a GraphQL API with Rails and GraphiQL

BharteeTechRubyOnRails
3 min read2 days ago

--

Introduction:

GraphQL is a powerful query language for APIs, and integrating it with Rails allows you to create flexible and efficient APIs. In this blog post, we’ll walk you through setting up a GraphQL API in a new Rails application, including how to use GraphiQL for testing and debugging.

Why Choose GraphQL Over REST?

  1. Fetch Only What You Need — No over-fetching or under-fetching.
  2. Fewer API Calls — Retrieve related data in one request.
  3. Strongly Typed Schema — Self-documenting and structured.
  4. No Versioning Needed — Evolve API without breaking changes.
  5. Real-time Support — Built-in subscriptions for live updates.

When to Use REST? Simpler for small projects & HTTP caching.

Setting Up the Rails Application

  1. Create a new Rails application:
rails new graphql-api --api
cd graphql-api

2. Install necessary gems:

bundle install
bundle add graphql

3. Install GraphQL:

rails generate graphql:install

This command will generate the necessary folders: mutations, resolvers, and types. The query_type.rb file in the types folder will include a default test field:

def test_field
"Hello World!"
end

Creating Models

  1. Generate User and Blog models:
rails g model user first_name last_name email
rails g model blog title description:text user:references

2. Update the user.rb model:

class User < ApplicationRecord
has_many :blogs, dependent: :destroy
before_save { self.email = email.downcase }
end

Seeding the Database

  1. Add the faker gem to your Gemfile:
gem 'faker'
bundle install

2. Add sample data to seeds.rb:

5.times do
first_name = Faker::Name.first_name
User.create!(first_name: first_name, last_name: Faker::Name.last_name, email: "#{@test.com">first_name}@test.com")
end

20.times do
Blog.create!(title: Faker::Book.title, description: Faker::Lorem.paragraphs(number: 3), user: User.find(User.ids.sample))
end

3. Create, migrate, and seed the database:

rails db:create db:migrate db:seed

Configuring GraphQL

  1. Update graphql_api_schema.rb:
class GraphqlApiSchema < GraphQL::Schema
mutation(Types::MutationType)
query(Types::QueryType)
end

2. Update types/query_type.rb:

module Types
class QueryType < Types::BaseObject
field :node, Types::NodeType, null: true, description: "Fetches an object given its ID." do
argument :id, ID, required: true, description: "ID of the object."
end

def node(id:)
context.schema.object_from_id(id, context)
end

field :nodes, [Types::NodeType, null: true], null: true, description: "Fetches a list of objects given a list of IDs." do
argument :ids, [ID], required: true, description: "IDs of the objects."
end

def nodes(ids:)
ids.map { |id| context.schema.object_from_id(id, context) }
end

field :test_field, String, null: false, description: "An example field added by the generator"
def test_field
"Hello World!"
end
end
end

Running a Test Query

  1. Add the graphiql-rails gem to your Gemfile:
gem 'graphiql-rails', group: :development
bundle install

2. Update routes.rb to mount GraphiQL:

if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end

3. Resolve the GraphiQL error:

If you encounter the following error:

RuntimeError in GraphiQL::Rails::Editors#show
GraphiQL::Rails requires either Propshaft or Sprockets. Use `$ bundle add propshaft` or `$ bundle add sprockets-rails` to add one of them to your app.

Add sprockets-rails:

bundle add sprockets-rails
mkdir -p app/assets/config
cd app/assets/config
touch manifest.js

Add the following lines to manifest.js:

//= link graphiql/rails/application.css
//= link graphiql/rails/application.js

Start the server and visit http://localhost:3000/graphiql: You should see the GraphiQL interface.

4. Run the test query:

Request:

{
testField
}

You should see the following output:

{
"data": {
"testField": "Hello World!"
}
}

By following these steps, you’ve set up a GraphQL API with Rails, created some sample data, and tested your setup with GraphiQL. This setup allows you to quickly iterate on your API and see changes reflected instantly, which is a huge advantage for development.

Happy coding!

--

--

BharteeTechRubyOnRails
BharteeTechRubyOnRails

Written by BharteeTechRubyOnRails

Ruby on Rails Developer || React Js || Rspec || Node Js

No responses yet