Setting up GraphQL

Now we have a sinatra app that connects to the database and shows a list of speakers as a JSON response. Now let’s add graphql and define a schema for speakers.

Add the graphql gem. https://github.com/rmosolgo/graphql-ruby.

Also the rack-contrib gem needs to be added so that the sinatra app can accept raw JSON payloads.

GraphQL works on a “schema” (basically something like a database schema), with the required models that needs to be queried or updated. So we need to define a schema.

require 'graphql'
require_relative 'query'
class ConferenceAppSchema < GraphQL::Schema
query QueryType
end
view raw schema.rb hosted with ❤ by GitHub

The /graphql endpoint

We now need to have a POST endpoint for GraphQL.

GraphQL schema can be executed to give a GraphQL::Query::Result which can then be converted to JSON. app.rb needs change to include this endpoint.

# Changes to file app.rb
# ...
require 'rack/contrib'
class ConferenceApp < Sinatra::Base
# ...
use Rack::PostBodyContentTypeParser
# ...
# ...
post '/graphql' do
result = ConferenceAppSchema.execute(
params[:query],
variables: params[:variables],
context: { current_user: nil },
)
json result
end
# ...
end
view raw app_5.rb hosted with ❤ by GitHub
Get notified on engineering articles like this

Follow us on twitter @neumeralhq