Skip to main content
This guide will get you from zero to a working GraphQL API in three simple steps. You’ll install the gem, define your first schema, and execute a query.

Before you begin

Make sure you have:
  • Rails 6.0 or higher
  • Ruby 2.6.3 or higher
  • An existing Rails application
1

Install Rails GraphQL

Add the gem to your Gemfile and run the Rails generator:
# Add the gem to your Gemfile
bundle add rails-graphql

# Run the Rails generator
rails g graphql:install
The generator creates:
  • app/graphql/app_schema.rb - Your main GraphQL schema
  • app/controllers/graphql_controller.rb - Controller to handle requests
  • Route configuration for /graphql endpoint
2

Define your schema

Open app/graphql/app_schema.rb and add a simple field that returns a greeting:
app/graphql/app_schema.rb
module GraphQL
  class AppSchema < GraphQL::Schema
    field(:welcome).resolve { 'Hello World!' }
  end
end
This creates a GraphQL field named welcome that returns the string “Hello World!” when queried.
You can also define fields with a block syntax:
query_fields do
  field(:welcome, :string, null: false)
end

def welcome
  'Hello World!'
end
3

Run your first query

Start your Rails server and execute a GraphQL query:
curl -d '{"query":"{ welcome }"}' \
     -H "Content-Type: application/json" \
     -X POST http://localhost:3000/graphql
In the Rails console, you’ll also see helpful log output:
GraphQL (0.4ms)  { welcome }
↳ (irb):1:in `<main>'

What you just built

Congratulations! You’ve created your first GraphQL API with Rails GraphQL. Here’s what happened:
  1. Installed the framework - The generator set up the necessary files and configuration
  2. Defined a schema - Created a GraphQL schema with a single query field
  3. Executed a query - Made a request and received a JSON response

Add more fields

Let’s expand your schema with additional fields:
app/graphql/app_schema.rb
module GraphQL
  class AppSchema < GraphQL::Schema
    query_fields do
      field(:welcome, :string, null: false)
      field(:current_time, :date_time, null: false)
      field(:greet, :string, null: false) do
        argument(:name, :string, null: false)
      end
    end

    def welcome
      'Hello World!'
    end

    def current_time
      Time.current
    end

    def greet(name:)
      "Hello, #{name}!"
    end
  end
end
Now you can query with arguments:
curl -d '{"query":"{ greet(name: \"Rails\") }"}' \
     -H "Content-Type: application/json" \
     -X POST http://localhost:3000/graphql
# {"data":{"greet":"Hello, Rails!"}}

Next steps

Architecture

Learn how Rails GraphQL integrates with Rails

Schemas

Understand schemas and how to organize your GraphQL API

Fields

Deep dive into defining and configuring fields

Types

Explore objects, interfaces, unions, and more
Don’t forget to add authentication and authorization to your GraphQL endpoint before deploying to production!

Build docs developers (and LLMs) love