Blog

GraphQL And Its Implementation in Ruby on Rails

Madhuri Shrestha
September 26, 2023

What is GraphQL?

GraphQL is an open-source query language for an API and a server-side runtime for executing those queries by specifying the data structure you need. It is suitable for Ruby on Rails and it allows clients to request only the data they require, reducing over-fetching and under-fetching of data. Instead of multiple endpoints for various resources like REST, GraphQL has a single endpoint that clients can query with precisely what they need.

Key Characteristics And Concepts Of GraphQL

Flexible Queries

In GraphQL, instead of the server defining the structure of the response, it allows clients to request exactly the data they need. Clients can specify the shape and depth of the data in a single query, reducing over-fetching and under-fetching of data.

Single Endpoint

In a GraphQL API, there is typically a single endpoint (usually /graphql) that clients use to send all their queries, mutations, and subscriptions. This simplifies the API surface and eliminates the need for multiple endpoints.

Strongly Typed

GraphQL APIs are strongly typed, meaning they have a well-defined schema that specifies the types of data that can be queried, including objects, scalars (like integers and strings), and more complex types. This schema serves as a documentation for the API and allows for powerful tooling, including autocompletion.

Versioning

Since clients request only the data they need, changes to the API schema don’t necessarily require versioning. This can make evolving an API more straightforward.

Batching

GraphQL allows clients to batch multiple queries into a single request. This reduces the overhead of multiple HTTP requests, improving efficiency.

Declarative Data Fetching

Clients declare their data requirements in a structured way, which makes it easier to understand and optimise data fetching on the server side.

Security

GraphQL allows fine-grained control over what data is exposed to clients. You can define permissions and validation rules to ensure that only authorised requests are fulfilled.

Let’s Add GraphQL to Your Rails Application

To incorporate GraphQL into your Rails project, you will want to use a gem like graphql-ruby. Open your Gemfile and add the following line:


gem 'graphql'

After adding the gem, run the bundle install command to install it:


bundle install

Getting Started

Run the following command to install initiate GraphQL in your application:


bundle install
rails generate graphql:install

You may need to run bundle install again, as by default the interface gem graphiql-rails is added on installation.


bundle install

This will provide us an interface in the route /graphiql where we can execute the GraphQL queries.

Creating GraphQL Types

In GraphQL, types define the shape of the data that can be queried. To create GraphQL types in your Rails application, you can generate them using the following command:


rails generate graphql:object TypeName

where TypeName is the name of the type you want to create.

This command will generate a file in the app/graphql/types directory with the type definition. For example, if you have a User model and you want to create an object type for it then you can run:


rails generate graphql:object User

You can also customise the fields of the object type by adding attributes from your model as fields in the GraphQL type definition. For example:


module Types
  class UserType < Types::BaseObject
    field :id, ID, null: false
    field :attrName1, String, null: true
    field :attrName2, Boolean, null: true
    field :attrName3, Integer, null: true
    # Add more fields as required
  end
end

where attrNameN is the attribute you want to include in the GraphQL object type.

You can also define associations and custom methods as fields in the GraphQL object type to fetch related data. Once GraphQL object type is defined, you can use it in your queries and mutations.

Defining Queries and Mutations

Queries and mutations are at the core of GraphQL, allowing clients to request data and make changes to the server’s data, respectively.

Query

Query allows us to get data. It represents the read in CRUD. We will define the query in the auto generated file app/graphql/types/query_type.rb like this:


field :user, Types::UserType do
  argument :id, ID
end

def user(id:)
  User.find(id)
end

Once this query is defined you can use the generated GraphQL object type in a query. Simply go to /graphiql and paste the query below and hit run. You should get the desired attributes for this type based on what you have requested in the query.


query {
  user(id: 1) {
    id
    attrName1
    attrName2
    # Add more fields as required
  }
}

Mutation

Mutation allows us to change information, including adding, updating, or removing data. It represents the create, update, and destroy in CRUD.

First, we will define the mutation type in the auto generated file app/graphql/types/mutation_type.rb like this:


field :create_object_type, mutation: Mutations::CreateObjectType

Then, we will define the mutations like this:


module Mutations
  class CreateObjectType < BaseMutation
    argument :input, InputType, required: true
    field :object, Types::ObjectType, null: true
    
    def resolve(input:)
      # Mutation logic here
    end
  end
end

Once the mutation is defined, just like when using query, we can go to /graphiql and run the mutation query to test it out. For example:


mutation {
  createObjectType(input: input){
    object {
      id
      attrName1
      attrName2
    }
  }
}

This would simply run the logic defined in the resolve method and return the requested attributes defined for object type.

Conclusion

In this introductory blog post, we got started with implementing the basics of GraphQL in Ruby on Rails. We’ve seen how GraphQL brings a fresh perspective to API development, offering powerful tools like queries and mutations to efficiently retrieve and manipulate data. With a single endpoint and a flexible schema, GraphQL empowers developers to craft APIs that are more responsive to client needs and easier to maintain. We are just scratching the surface in this article. As we delve deeper into the realm of GraphQL in Ruby on Rails, we will explore the practical implementation of these concepts and witness the transformative impact they can have on your web application development process.

If you would like more information or help with your Ruby on Rails project, please contact us and we will be happy to help.