Installing GraphQL API with Ruby on Rails
🧠 Technical Summary
In this guide, you will learn how to set up a GraphQL supported API on the Ruby on Rails framework. The aim is to eliminate redundant data retrieval problems in REST APIs and ensure that clients receive only the data they need in a single query. Steps: Installing Rails API application, installing GraphQL gems, creating Note model and types, defining queries and mutations.
🎯 What Will You Learn in This Guide?
- Creating a Rails API application compatible with PostgreSQL,
- Establishing a query environment using GraphQL and GraphiQL gems,
- Defining the Note model, queries (fetchNotes, fetchNote) and mutations (addNote),
- Testing your API via GraphiQL IDE.
⚙️ Step by Step GraphQL API Installation
1. Creating a New Rails API Application
Start a new API-based project:
rails new rails_graphql -d=postgresql -T --api
cd rails_graphql
📝 This command creates an API project using PostgreSQL, without test files.
Create the database:
rails db:create
📝 Creates development and test databases using the settings in config/database.yml.
2. Setting Up GraphQL Environment
Add GraphQL gems to the Gemfile file:
gem 'graphql'
group :development do
gem 'graphiql-rails'
end
Install gems:
bundle install
Create the GraphQL infrastructure:
rails g graphql:install
📝 This command adds the necessary files and endpoint for GraphQL configuration.
Enable GraphiQL IDE: Add to config/routes.rb:
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end
post "/graphql", to: "graphql#execute"
📝 In this way, query tests can be performed via the browser at /graphiql.
Enable browser support: In the file config/application.rb, uncheck # at the beginning of this line:
require "sprockets/railtie"
Create manifest.js:
mkdir -p app/assets/config
nano app/assets/config/manifest.js
Add the following:
//= link graphiql/rails/application.css
//= link graphiql/rails/application.js
3. Creating Model and GraphQL Types
Create Note model:
rails generate model note title:string:index body:text
rails db:migrate
Create the note type:
rails generate graphql:object Note id:ID! title:String! body:String!
Add input type (for Mutations): Create app/graphql/types/input/note_input_type.rb:
module Types
module Input
class NoteInputType < Types::BaseInputObject
argument :title, String, required: true
argument :body, String, required: true
end
end
end
4. Writing GraphQL Queries
Create the BaseQuery class:
module Queries
class BaseQuery < GraphQL::Schema::Resolver
end
end
Query that fetches all notes (fetchNotes):
module Queries
class FetchNotes < Queries::BaseQuery
type [Types::NoteType], null: false
def resolve
Note.all.order(created_at: :desc)
end
end
end
Query that retrieves a single note with ID (fetchNote):
module Queries
class FetchNote < Queries::BaseQuery
type Types::NoteType, null: false
argument :id, ID, required: true
def resolve(id:)
Note.find(id)
rescue ActiveRecord::RecordNotFound
GraphQL::ExecutionError.new('Not bulunamadı.')
end
end
end
Add to QueryType:
field :fetch_notes, resolver: Queries::FetchNotes
field :fetch_note, resolver: Queries::FetchNote
5. Writing GraphQL Mutations
New annotation mutation (addNote):
module Mutations
class AddNote < Mutations::BaseMutation
argument :params, Types::Input::NoteInputType, required: true
field :note, Types::NoteType, null: false
def resolve(params:)
note = Note.create!(params.to_h)
{ note: note }
rescue ActiveRecord::RecordInvalid => e
GraphQL::ExecutionError.new("Geçersiz veri: #{e.record.errors.full_messages.join(', ')}")
end
end
end
Add to MutationType:
field :add_note, mutation: Mutations::AddNote
6. Testing via GraphiQL
Go to http://localhost:3000/graphiql and try these queries:
📘 Get All Notes:
query {
fetchNotes {
id
title
body
}
}
📝 Get Single Note with ID:
query {
fetchNote(id: 1) {
id
title
body
}
}
➕ Add New Note:
mutation {
addNote(input: { params: { title: "GraphQL Notu", body: "GraphQL ile not ekleme örneği" }}) {
note {
id
title
body
}
}
}
❓ Frequently Asked Questions (FAQ)
1. Why is GraphQL more flexible than REST?
Because GraphQL allows the client to retrieve only the fields it needs in a single request.
2. What is GraphiQL?
GraphiQL is an interactive IDE that allows you to test GraphQL queries via the browser.
3. What does rails new --api do?
It starts Rails with a lightweight configuration suitable only for API development.
4. Can I use SQLite instead of PostgreSQL?
Yes, but in large-scale projects PostgreSQL is more stable and performant.
5. Should GraphiQL remain open in the production environment?
No, just enable it in the development environment.
🎯 Result
You have now learned how to develop a GraphQL-based API on Ruby on Rails. You can easily test note creation, listing and query operations via GraphiQL.
💡 Try your GraphQL-supported Rails APIs on high-performance servers on the GenixNode platform now!

