GraphQL API in a Rails Application

Total Blog Views: 64

Blog Status: publish

Created By: swaz_ahmed Created at: 07-01-2024

Tags: ruby on rails graphql

Introduction

In the ever-evolving software development landscape, efficient data-fetching mechanisms are paramount. Shadbox Info System Pvt Ltd, a leading company specializing in Ruby on Rails (RoR) technology, has recently embraced GraphQL to enhance its API capabilities. This blog delves into the process of integrating GraphQL into a Rails application, highlighting the benefits and providing a step-by-step guide to implementation.

What is GraphQL?

GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. It was developed by Facebook in 2012 and open-sourced in 2015. Unlike REST APIs, GraphQL allows clients to request only the data theGraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. It was developed by Facebook in 2012 and open-sourced in 2015. Unlike REST APIs, GraphQL allows clients to request only the data they need, reducing over-fetching and under-fetching of data.y need, reducing over-fetching and under-fetching of data.

Why Chose GraphQL

Using traditional REST APIs for their applications. However, they faced several challenges:

  • Over-fetching Data: REST APIs often return more data than needed, leading to inefficiencies.
  • Under-fetching Data: Sometimes multiple endpoints are required to fetch the necessary data.
  • Versioning Issues: Managing different versions of the API was becoming cumbersome.

 GraphQL solved these problems by allowing clients to specify exactly what data they needed, all in a single request.

Setting Up a Rails Application with GraphQL

Step 1: Creating a New Rails Application
First, we need to create a new Rails application. Open your terminal and run:

 

 rails new shadbox_graphql_app
 cd shadbox_graphql_app

Step 2: Adding GraphQL Dependencies
Next, add the graphql gem to your Gemfile:

 

 # Gemfile
gem 'graphql'

 Run bundle install to install the gem.

Step 3: Generating GraphQL Files

To generate the necessary GraphQL files, run:

 

rails generate graphql:install

This command creates several files and folders, including:

  • ​'app/graphql/types/'
  • 'app/graphql/mutations/'
  • 'app/graphql/shadbox_graphql_app_schema.rb'

Step 4: Defining Your Types
GraphQL uses types to define the shape of your data. Let's create a User type as an example. First, generate a User model:

 

rails generate model User name:string email:string
rails db:migrate

 Now, define the UserType:

 

# app/graphql/types/user_type.rb
module Types
  class UserType < Types::BaseObject
    field :id, ID, null: false
    field :name, String, null: false
    field :email, String, null: false
  end
end

Step 5: Creating Query Types
Next, let's create a query type to fetch users:

 

# app/graphql/types/query_type.rb
module Types
  class QueryType < Types::BaseObject
    field :users, [UserType], null: false
    
    def users
      User.all
    end
  end
end

 Update your schema to include the query type:

 

# app/graphql/shadbox_graphql_app_schema.rb
class ShadboxGraphqlAppSchema < GraphQL::Schema
  query(Types::QueryType)
end

 

Step 6: Creating Mutation Types

To modify data, we need to define mutations. Let's create a mutation to add a new user:

 

# app/graphql/mutations/create_user.rb
module Mutations
  class CreateUser < BaseMutation
    argument :name, String, required: true
    argument :email, String, required: true

    field :user, Types::UserType, null: false
    field :errors, [String], null: false

    def resolve(name:, email:)
      user = User.new(name: name, email: email)
      if user.save
        {
          user: user,
          errors: []
        }
      else
        {
          user: nil,
          errors: user.errors.full_messages
        }
      end
    end
  end
end 

 Update your mutation type:

# app/graphql/types/mutation_type.rb
module Types
  class MutationType < Types::BaseObject
    field :create_user, mutation: Mutations::CreateUser
  end
end

Update your schema to include the mutation type:
 

 # app/graphql/shadbox_graphql_app_schema.rb
class ShadboxGraphqlAppSchema < GraphQL::Schema
  mutation(Types::MutationType)
  query(Types::QueryType)
end

Step 7: Setting Up the GraphQL Controller
Create a GraphQL controller to handle incoming requests:

 

rails generate controller graphql

 Update the controller:

 

# app/controllers/graphql_controller.rb
class GraphqlController < ApplicationController
  def execute
    variables = ensure_hash(params[:variables])
    query = params[:query]
    operation_name = params[:operationName]
    context = {
      # Query context goes here, for example:
      # current_user: current_user,
    }
   result = ShadboxGraphqlAppSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
    render json: result
  rescue StandardError => e
    handle_error_in_development(e)
  end

private

def ensure_hash(ambiguous_param)
    case ambiguous_param
    when String
      if ambiguous_param.present?
        JSON.parse(ambiguous_param)
      else
        {}
      end
    when Hash, ActionController::Parameters
      ambiguous_param
    when nil
      {}
    else
      raise ArgumentError, "Unexpected parameter: #{ambiguous_param}"
    end
  end

def handle_error_in_development(e)
    logger.error e.message
    logger.error e.backtrace.join("\n")
    render json: { error: { message: e.message, backtrace: e.backtrace }, data: {} }, status: 500
  end
end

 

Step 8: Routing

Add the GraphQL endpoint to your routes:

 

# config/routes.rb
Rails.application.routes.draw do
  post "/graphql", to: "graphql#execute"
end

Testing the GraphQL API
With the server running (rails s), you can test your GraphQL API. Use a tool like GraphiQL to send a query:

Querying Users
Send the following query to fetch all users:

 

{
  users {
    id
    name
    email
  }
}

 You should see a list of users in the response.

Creating a User
To create a new user, send the following mutation:

 

mutation {
  createUser(input: { name: "John Doe", email: "[email protected]" }) {
    user {
      id
      name
      email
    }
    errors
  }
}

You should see the new user's details in the response, along with an empty array for errors if the creation was successful.

Conclusion
Integrating GraphQL into a Rails application can significantly enhance data fetching efficiency and flexibility. By adopting GraphQL, you can streamline your API operations, providing a more robust and user-friendly interface for clients. This guide serves as a testament to the power of GraphQL and its potential to transform modern web development practices.

 


swaz_ahmed

I am swaz_ahmed blogger on shadbox. I am influencer,content writer,author and publisher. Feel free to ask me any question and suggestions.



Comments



Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads