GraphQL Api With Rails

Written by colinjfw | Published 2016/10/01
Tech Story Tags: graphql | rails | ruby | api

TLDRvia the TL;DR App

Graphql is an awesome new technology which is making it easier for clientside developers to iterate quickly and batch together network requests.

I really like the promise provided by GraphQl however it is not as easyas rest to get up and running on immediately. This blog post takes a lookat how to build a working GraphQL backend in just a few steps using rails.

I am using my own project graphql-api as a framework for building out the GraphQL backend.

We will look at building a basic blogging application. A blog will havean author and some tags.

First create the rails backend.

rails new blog-api --api

Add the necessary libraries to the Gemfile

gem 'graphql'gem 'graphql-api'

Create our models

rails g model Author name:stringrails g model Blog title:string content:text author:referencesrails db:migrate

Add our has many relations to author class

class Authorhas_many :blogsend

Great! Now we have a basic setup for our blogging backend. Let's add somecontrollers to serve basic Graphql queries.

Add the following file to app/controllers/graphql_controller.rb.

class GraphqlController < ApplicationControllerSCHEMA = GraphQL::Api::Schema.new.schema

def createrender json: SCHEMA.execute(params[:query],variables: params[:variables] || {},)end

end

Add the following route to config/routes.rb

resources :graphql, only: :create

Now let's test out the new api with curl. Start up the server and run thefollowing command to see if we have any blog posts

curl -XPOST -d 'query=query { blogs { id } }' \localhost:3000/graphql

{"data":{"blogs":[]}}

Let's create an author

curl -XPOST \-d 'query=mutation {createAuthor(input: {name: "foobar"}) {author { id }}}' localhost:3000/graphql

{"data":{"createAuthor":{"author":{"id":1}}}}

Now let's create a blog with that author's id

curl -XPOST \-d 'query=mutation {createBlog(input: {title: "foobar", author_id: 1}) {blog { id }}}' localhost:3000/graphql

{"data":{"createBlog":{"blog":{"id":1}}}}

Let’s try that first query again, but this time let’s try and return the blog authors as well as the blog name.

curl -XPOST -d 'query=query {blogs {idtitlecontentauthor {name}}}' localhost:3000/graphql

You can also run updateBlog mutations as well as updateAuthor mutations. Try deleting an author or blog and see what responses you get back.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Published by HackerNoon on 2016/10/01