You can install graphql
from RubyGems by adding to your application’s Gemfile
:
# Gemfile
gem "graphql"
Then, running bundle install
:
$ bundle install
On Rails, you can get started with a few GraphQL generators:
# Add graphql-ruby boilerplate and mount graphiql in development
rails g graphql:install
# Make your first object type
rails g graphql:object Post title:String rating:Int comments:[Comment]
Or, you can build a GraphQL server by hand:
Types describe objects in your application and form the basis for GraphQL’s type system.
# app/graphql/types/post_type.rb
module Types
class PostType < Types::BaseObject
description "A blog post"
field :id, ID, null: false
field :title, String, null: false
# fields should be queried in camel-case (this will be `truncatedPreview`)
field :truncated_preview, String, null: false
# Fields can return lists of other objects:
field :comments, [Types::CommentType], null: true,
# And fields can have their own descriptions:
description: "This post's comments, or null if this post has comments disabled."
end
end
# app/graphql/types/comment_type.rb
module Types
class CommentType < Types::BaseObject
field :id, ID, null: false
field :post, PostType, null: false
end
end
Before building a schema, you have to define an entry point to your system, the “query root”:
class QueryType < GraphQL::Schema::Object
description "The query root of this schema"
# First describe the field signature:
field :post, PostType, null: true do
description "Find a post by ID"
argument :id, ID, required: true
end
# Then provide an implementation:
def post(id:)
Post.find(id)
end
end
Then, build a schema with QueryType
as the query entry point:
class Schema < GraphQL::Schema
query QueryType
end
This schema is ready to serve GraphQL queries! Browse the guides to learn about other GraphQL Ruby features.
You can execute queries from a query string:
query_string = "
{
post(id: 1) {
id
title
truncatedPreview
}
}"
result_hash = Schema.execute(query_string)
# {
# "data" => {
# "post" => {
# "id" => 1,
# "title" => "GraphQL is nice"
# "truncatedPreview" => "GraphQL is..."
# }
# }
# }
See Executing Queries for more information about running queries on your schema.
If you’re building a backend for Relay, you’ll need:
GraphQL::Introspection::INTROSPECTION_QUERY
GraphQL::Relay
guides.Apollo Client is a full featured, simple to use GraphQL client with convenient integrations for popular view layers. You don’t need to do anything special to connect Apollo Client to a graphql-ruby
server.
GraphQL.js Client is a tiny client that is platform- and framework-agnostic. It works well with graphql-ruby
servers, since GraphQL requests are simple query strings transported over HTTP.