Seeding your rails backend using an external API

Daniel Patnode
3 min readOct 6, 2020
seeds

for my final project at Flatiron school one of the base requirements was to implement an external API and use the information gained from this to populate the content of my app. With a bit of experience and a whole bunch of gumption I set off on my voyage to grab all the information I could. Below is a detailed account of my experience grabbing information that would in tern be used as the base data for my final project.

to start off I began by creating a basic rails backend by running:

rails new practice_api_call api — database=postgresql

and let my computer go to work setting up a rails.

when that was completed I navigated to my Gemfile and added the following gems, preceded by bundle install:

gem 'rack-cors'
gem 'active_model_serializers'
gem 'rest-client', '~> 2.1'

I then navigated to the cors.rb file and added the following code to make sure the information could be passed to my frontend:

Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do
origins '*'
resource '*',headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end

from there, the next step was creating a model with column names matching the same information provided by the external API I was grabbing from (in this case https://api.openbrewerydb.org/breweries) which I grabbed by passing into insomnia. The returned data in JSON format looked like this:

Data from the API in insomnia

my migration file in turn looked like this:

With that all set up the next step was to navigate to my seeds.rb file and make a request to the external API:

and from there I used the create method within a .each to make each individual brewery.

at this point the only thing left to do was run rails db:seed which left me with a ton of information to work with for my project!

all the beautiful breweries

in very few lines of code I was able to seed my project without having to do an extensive amount of data entry.

--

--