Using The Rest-Client Gem to Seed Data in Rails

Cristina Cristobal
2 min readJun 14, 2019

I’m currently wrapping up my 11th week at Flatiron School’s Software Engineering program. For my Mod 4 project my partner and I are building a Rick and Morty resource app where users will be able to learn more about the characters of the show.

One of the items discussed during the planning phase was how we were going to build out our backend. Luckily, my partner found a Rick and Morty API that we would be able to use for our project (https://rickandmortyapi.com/api/character/). We could not, however, simply fetch the data to use. We would need to seed that data into our own database.

After consulting with one of the Software Engineer Coaches, I learned that we could use the RestClient gem to seed our data from the existing API. So rather than manually creating each instance of a character, I was able to run a few lines of code that would seed the data according to the database structure. Here’s how it was done:

  1. Add the rest-client gem to Gemfile
gem ‘rest-client’

2. ‘bundle install’ in the terminal

bundle install

3. create your MVC files and database using ‘rails g resource’

rails g resource Character name status species gender image

4. create and migrate your database

rails db:createrails db:migrate

Next, to properly seed your data, you’ll have to include the following lines of code in your seeds.rb file.

5. require the RestClient gem

require ‘rest-client’

6. call RestClient.get to the API URL

rm = RestClient.get ‘https://rickandmortyapi.com/api/character/'

(Here, I saved the get request to the variable ‘rm’ )

Note: I found it helpful to call ‘byebug’ right beneath this line of code to play around with the response received. By playing with the return in the console I was able to find out that the data I needed was in the second key of the hash titled “results.” Given the structure of that data, I did the following:

7. parse the data and save it as JSON

rm_array = JSON.parse(rm)[“results”]

At this point, I have all the data in the API I need to work with, which is a large array with character data.

At this point I am ready to seed the character data into my Rails backend. To do this I simply have to…

8. create a new instance of character for each character in the returned array

rm_array.each do |character|
Character.create(
name: character[“name”],
status: character[“status”],
species: character[“species”],
gender: character[“gender”],
image: character[“image”]
)
end

9. seed the data

rails db:seed 

10. create the index method in the controller

def index
render({json: Character.all})
end

12. run rails s to start the server

rails s

13. open the route provided (localhost:[port])

And there you go! You should see your newly seeded data with the structure you provided!

--

--