GraphQL Queries

Add type, query and schema for graphql

Now we need to add a type for Speaker, also a query and a schema for GraphQL.

require 'graphql'
require_relative 'base_object'
class Types::Speaker < Types::BaseObject
description 'Resembles a Speaker Object Type'
field :id, ID, null: false
field :name, String, null: false
field :twitter_handle, String, null: true
field :bio, String, null: true
field :talk_title, String, null: true
end
view raw speaker.rb hosted with ❤ by GitHub

We need to then add a root query in query.rb file.

require 'graphql'
require_relative 'types/speaker'
class QueryType < GraphQL::Schema::Object
description "The query root of this schema"
field :speakers, [Types::Speaker], null: false do
description 'Get all speakers of the system'
end
def speakers
Speaker.all
end
end
view raw query.rb hosted with ❤ by GitHub

And include the query in the schema.

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

Querying the endpoint

You can use the GraphiQL app or the Postman app to query the endpoint. Make sure that you have puma running and the server is up.

Postman Query Graphql

A JSON response like the below will be obtained.

{
"data": {
"speakers": [
{
"name": "John",
"twitterHandle": "johnruby",
"bio": "This is John's bio"
},
{
"name": "Jacob",
"twitterHandle": "jacob-ruby",
"bio": "This is Jacob\\'s bio"
}
]
}
}
view raw response.json hosted with ❤ by GitHub

Now you have a GraphQL server up and running on sinatra, and you can query the endpoint to get a list of speakers with the fields defined in the GraphQL query.

In the next part we will add mutations.

Get notified on engineering articles like this

Follow us on twitter @neumeralhq