How to create a GraphQL API with Rails 7

Migrate an existing Rest API or create a new one

Posted on August 08, 2023
Using GraphQL as a query language allows more flexibility when consuming any API. Migrating existing APIs to GraphQL or creating a new one can be an attractive alternative

Here we will use the approach of migrating an existing API that uses JWT as the authentication method. The first step is to install the GraphQL Ruby gem. After following the instructions to install the gem, generate the initializer and the schema:


rails generate graphql:install

Define  Type `User`

The first step is to create a new type for the GraphQL handle users and enable the authentication process with a mutation, this object is different object from our User model of Active Record on our app folder.

Create a file app/graphql/types/user_type.rb with the following content:



module Types
  class UserType < Types::BaseObject
    field :id, ID, null: false
    field :email, String, null: false 
  end
end

Create a mutation to authenticate


The next step is to create a mutation to authenticate using the User type created previously, will still using JWT as the authorization method but using GraphQL as the API engine.

Create a file app/graphql/mutations/user_login.rb with the following content:



module Mutations
  class UserLogin < BaseMutation    
    argument :email, String, required: true
    argument :password, String, required: true
    field :token, String, null: true
    field :user, Types::UserType, null: true
    field :errors, [String], null: false
    
    def resolve(email:, password:)
      user = User.find_for_authentication(email: email)
      if user&.valid_password?(password)
        # Assuming you have a method to generate a token
        token = user.generate_jwt
        {          
          user: user,          
          token: token,          
          errors: []
         }
      else
       { 
         user: nil,
         token: nil,
         errors: ["Invalid email or password"]
       }
      end
    end
  end
end

Install graphiql to testing


Once we build the mutation for login, we must proceed to install the graphiql gem for testing mutations and queries on dev environment and following the initialization instructions:


bundle add graphiql-rails
When the gem is installed and setup can access to this on /graphiql



Validate login mutation

Using graphiql tool we test our login mutation with valid credentials:


mutation{
  login(input: { email: "test_email", password: "password"}) {
    token
  }
}
 

Create Order Type and Article Type

We need a new type type to create a new query to retrieve the order associated to the user, using the API structure of the JWT API so we create a new object named order_type on /app/graphql/types/order_type.rb


module Types
  class OrderType < Types::BaseObject
    field :id, ID, null: false
    field :article, Types::ArticleType
    field :total, Float
    field :quantity, Integer
    field :created_at, GraphQL::Types::ISO8601DateTime, null: false
    field :updated_at, GraphQL::Types::ISO8601DateTime, null: false
    field :user, Types::UserType
  end
end
A new article type object.


module Types
 class ArticleType < Types::BaseObject
    field :id, ID, null: false
    field :name, String
    field :price, Float
    field :integer, Integer
    field :stock, Integer
  end
end


Create queries for retrieve data


Now we are ready to create queries to retrieve data, using the API structure of the JWT API, we will create a order query for retrieve user orders, so we must create a new query on /app/graphql/types/query_type.rb file:



 field :orders, [Types::OrderType], null: false
 def orders
   context[:current_user].orders
 end



Final Considerations


Now we are ready to create new queries and mutations to create or retrieve data, one final consideration can be handling authorizations and exceptions on graphql, we can reuse some of the policies that we implemented on out API's using can can or pundit.