Setup Links

In order to be able to show all links, you first need to set up your database so the links can be stored.

This generates a link.rb file in app/models that will look as follows:

class Link < ApplicationRecord

This is our link model.

Awesome! You now have a database table to store the links and a few dummy records setup.

Query for Returning Links

Now, go ahead and define your GraphQL Type for links. GraphQL Ruby uses a DSL for that.

Query Resolver

The type is now defined, but the server still doesn’t know how to handle it. To fix that, you will now write your first resolver. Resolvers are functions that the GraphQL server uses to fetch the data for a specific query. Each field of your GraphQL types needs a corresponding resolver function. When a query arrives at the backend, the server will call those resolver functions that correspond to the fields that are specified in the query.

All GraphQL queries start from a root type called Query.

When you previously ran rails generate graphql:install, it created the root query type in app/graphql/types/query_type.rb for you.

Resolvers can be either of two things:

  • object responding to call method accepting 3 arguments - obj, arg, ctx (like lambda or Proc objects)
  • GraphQL::Function - we are going discuss those in the next chapter

Testing With Playground

It’s time to check what you’ve done so far! For this, you’ll use GraphiQL, an in-browser IDE for running GraphQL queries.

GraphiQL had already been added to your application when you executed rails generate graphql:install in the terminal before, so you don’t have to do any extra work to set it up.

Open your browser at http://localhost:3000/graphiql

You’ll see a nice IDE that looks like this:

Click on the Docs link at the upper right to see a generated documentation of your schema. You’ll see the Query type there, and clicking it will show you the new allLinks field, exactly as you’ve defined it. The documentation in GraphiQL is generated automatically based on your schema. This works thanks to a mechanism called Introspection.

Try it out! On the left-most text box, type a simple query for listing all links and hit the Play button. This is what you’ll see:

You can play around as much as you want with this tool. It makes testing GraphQL APIs so fun and easy, you’ll never want to live without it any more. 😎

Next Chapter


Learn best practices for implementing GraphQL mutations with Ruby and graphql-ruby. You can test your implementation in a GraphiQL Playground.

Go to next chapter