Utilizing ‘Rest-client’ gem to set unique id’s to objects

Have you ever needed to utilize an endpoint with objects that did not contain unique ids? The ‘rest-client’ is a great gem to utilize to parse these objects to seed into your seed file so you can assign an id and save in your database.

This gem is a simple HTTP and REST client utilized in Ruby applications. Here is how I utilized this gem to be able to make post and delete requests.

NB: Make sure that you have already set up your models, controllers, created some tables. A handy command to generate these resources is:

rails g resources Recipe title img_url ingredients directions 

Set up serializers so you view these parsed JSON objects:

Include in Gemfile:

gem 'active_model_serializers', '~> 0.10.2'

Terminal command:

gem install active_model_serializers -v 0.10.2

Generate these files in the same way:

rails g serializer recipe

Make sure to add the attributes (keys) that you want to access

class MemberSerializer < ActiveModel::Serializer  
attributes :id, :title, :image_url, :ingredients, :directions
end
  1. Install ‘rest-client’ gem

Include in your Gemfile:

gem 'rest-client', '~> 1.8'

cd to your backend folder and run in terminal:

gem install rest-client -v 1.8.0

2. Add to seed.rb:

Make sure to require ‘rest-client’ & ‘json

require 'rest-client'
require 'json'

If you wanted to see what these objects are in your console, you can require ‘pry’ (again, make sure it is installed) and make sure it is returning the appropriate objects. Make sure the keys match the CORS enabled endpoint.

4. Migrate tables and seed data

rails db:migrate && rails db:seed

5. Check your server and voila!

rails s

You should now see these objects in your backend server with assigned and unique keys!

Fullstack Software Engineer | Musician | Food Lover | Coffee Addict