Published on
2 min read

A GraphQL server implementation - Ruby On Rails

Authors

GraphQL is a query language for APIs developed by the Facebook team. It gives clients the power to ask for exactly what they need, making it easier to evolve APIs over time and enabling powerful developer tools.

Video courtesy: graphql.org

A GraphQL request can be either a query (read) or a mutation (write). The request is a simple string that a GraphQL service interprets and resolves with data.

Key Features

  • No Over-fetching: Retrieve only the data your client needs.
  • Single Round-trip: Get many resources in a single request.
  • Strongly Typed: Describe your API with a type system.
  • No Versioning: Evolve your API without breaking changes.

GraphQL server implementation in Rails

Install the necessary gems:

# Gemfile
gem "graphql"
gem 'graphiql-rails', group: :development

Run the generator:

rails g graphql:install

This sets up the folder structure in app/graphql/, defines a schema, and adds a query type and route.

Defining Types

Add article_type.rb in app/graphql/types/:

ArticleType = GraphQL::ObjectType.define do
  name "Article"
  field :id, types.Int
  field :title, types.String
  field :body, types.String
  field :comments, types[CommentType]
end

Building the Schema

Define your entry point in app/graphql/types/query_type.rb:

QueryType = GraphQL::ObjectType.define do
  name "Query"
  description "The query root of this schema"

  field :article do
    type ArticleType
    argument :id, !types.ID
    description "Find an Article by ID"
    resolve ->(obj, args, ctx) { Article.find_by_id(args["id"]) }
  end
end

Update your schema definition:

# app/graphql/graphql_ruby_sample_schema.rb
GraphqlRubySampleSchema = GraphQL::Schema.define do
  query QueryType
end

Autoloading

In config/application.rb:

config.autoload_paths << Rails.root.join('app/graphql')
config.autoload_paths << Rails.root.join('app/graphql/types')

Example Query

query {
  article(id: 1) {
    title
  }
}
GraphiQL Example

You can find the sample code here.

TwitterLinkedInHacker News