Connecting to the Cost-of-Living API

For our app to show relevant cost-of-living data for whatever city a user inputs, we have to fetch it via an API call to this API. Create a free RapidAPI account to access it if you haven’t done so.

We’ll make the API call using the Faraday gem. Add it to the Gemfile and run bundle install.

ruby

# Gemfile gem 'faraday'

With that done, we now include the API call logic in the results method.

ruby

# app.rb ... get '/results' do city = params[:city] country = params[:country] # if country or city names have spaces, process accordingly esc_city = ERB::Util.url_encode(country) # e.g. "St Louis" becomes 'St%20Louis' esc_country = ERB::Util.url_encode(country) # e.g. "United States" becomes 'United%20States' url = URI("https://cost-of-living-prices-by-city-country.p.rapidapi.com/get-city?city=#{esc_city}&country=#{esc_country}") conn = Faraday.new( url: url, headers: { 'X-RapidAPI-Key' => ENV['RapidAPIKey'], 'X-RapidAPI-Host' => ENV['RapidAPIHost'] } ) response = conn.get @code = response.status @results = response.body erb :results end ...

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *