Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

Mutations with the graphql-client Ruby gem

The graphql-client is a really good library to consume Graphql APIs in Ruby.

You can execute a mutation the same way as if it was a regular query passing the variables you want to use:

require 'graphql/client'
require 'graphql/client/http'

module Api
  HTTP = GraphQL::Client::HTTP.new(ENV['GRAPHQL_API_URL'])
  Schema = GraphQL::Client.load_schema(HTTP)
  Client = GraphQL::Client.new(schema: Schema, execute: HTTP)
end

CreateCityMutation = Api::Client.parse(<<~'GRAPHQL')   
  mutation($name: String) {
    createCity(name: $name) {
      id
    }
  }
GRAPHQL

variables = {name: 'Jacksonville'}
result = Api::Client.query(CreateCityMutation, variables: variables)
puts result.data.create_city.id
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.