Introduction to GraphQL Server

Introduction to GraphQL with graphql-ruby and Sinatra

In this lesson, we will define basic types and write simple queries in GraphQL using graphql-ruby and Sinatra. By the end, you'll have created a basic GraphQL server to fetch a list of books, building on what you've learned about setting up a GraphQL server.

Creating the GraphQL Server

We'll start by setting up a new GraphQL server using graphql-ruby and Sinatra to manage our GraphQL endpoint. Let's do it step by step.

  1. Define the GraphQL schema:

    Ruby
    require 'sinatra'
    require 'graphql'
    require 'json'
    
    class BookType < GraphQL::Schema::Object
      field :title, String, null: true
      field :author, String, null: true
    end
    
    class QueryType < GraphQL::Schema::Object
      field :books, [BookType], null: false
    
      def books
        [
          { title: 'The Hobbit', author: 'J.R.R. Tolkien' },
          { title: 'Harry Potter', author: 'J.K. Rowling' }
        ]
      end
    end
    
    class MySchema < GraphQL::Schema
      query QueryType
    end

    In this schema:

    • The BookType class defines a book type with title and author fields, both of which are strings.
    • The QueryType class includes a books field that returns an array of book objects.
    • The resolver for the books query returns an array of book hashes.
  2. Initialize and configure the server:

    Ruby
    set :port, 4000
    
    post '/graphql' do
      request_payload = JSON.parse(request.body.read)
      query = request_payload['query']
      variables = request_payload['variables'] || {}
    
      result = MySchema.execute(query, variables: variables)
      content_type :json
      result.to_json
    end
    
    puts "🚀 Server ready at http://localhost:4000/graphql"

    This code:

    • Sets up a Sinatra server listening on port 4000.
    • Creates a POST endpoint at /graphql that accepts GraphQL queries.
    • Parses the incoming request, executes the query against our schema, and returns the result as JSON.

Running Queries Against the Server

With the server running, let's write and execute a query to fetch the list of books.

Ruby
require 'net/http'
require 'json'

query = <<~GRAPHQL
  query {
    books {
      title
      author
    }
  }
GRAPHQL

uri = URI('http://localhost:4000/graphql')
http = Net::HTTP.new(uri.host, uri.port)

request = Net::HTTP::Post.new(uri.path, { 'Content-Type' => 'application/json' })
request.body = { query: query }.to_json

response = http.request(request)
data = JSON.parse(response.body)

puts JSON.pretty_generate(data)

This script:

  • Uses the <<~GRAPHQL heredoc syntax to define a multi-line string for the query. The <<~ allows you to write the query across multiple lines with proper indentation, making it more readable than a single-line string. The GRAPHQL is just a delimiter (you could use any word) that marks where the string ends. The ~ character means Ruby will automatically remove leading whitespace, keeping your code clean.
  • Sends a POST request to the server with a query to fetch books.
  • Logs the response, which should include the list of books with their titles and authors.

The script outputs:

JSON
{
  "data": {
    "books": [
      {
        "title": "The Hobbit",
        "author": "J.R.R. Tolkien"
      },
      {
        "title": "Harry Potter",
        "author": "J.K. Rowling"
      }
    ]
  }
}

This output confirms that our server correctly handles the query and returns the expected data.

Lesson Summary

In this lesson, we:

  • Created a schema with a basic type (Book).
  • Set up resolvers to fetch data.
  • Wrote and ran queries to retrieve a list of books.

Next, you will practice what you've learned by tackling exercises that help solidify these concepts. The following lessons will cover more complex queries and mutations.

Happy coding!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal