jsonrubyhashbackendhttpbackend

Saving multiple api response in a single object in Ruby


I have a scenario where I need to convert multiple API responses into one object. Is it possible how? Below is my code. How do I convert it into one single object?

require 'httparty'
require 'json'

def make_request(url)
  HTTParty.get(url, headers: { 'Accept' => 'application/json' }).parsed_response
end

numberone_apis = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code}&cnt={cnt}&appid={API key}')

numbertwo_apis= make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code},{country code}&cnt={cnt}&appid={API key}')


numberthree_apis = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name}&cnt={cnt}&appid={API key})


puts numberone_apis
puts numbertwo_apis
puts numberthree_apis

convert_object2one = how ? 


Solution

  • Due to missing information on how the single responses look I can only recommend to build a new object. This answer is not optimized and highly opinionated based on the small given information.

    require 'httparty'
    require 'json'
    
    def make_request(url)
      HTTParty.get(url, headers: { 'Accept' => 'application/json' }).parsed_response
    end
    
    whole_response = {}
    
    whole_response['numberone_apis'] = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code}&cnt={cnt}&appid={API key}')
    
    whole_response['numbertwo_apis'] = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name},{state code},{country code}&cnt={cnt}&appid={API key}')
    
    whole_response['numberthree_apis'] = make_request('api.openweathermap.org/data/2.5/forecast/daily?q={city name}&cnt={cnt}&appid={API key}')
    
    puts whole_response 
    
    #=> 
    {
      'numberone_apis':
        { ... },
      'numbertwo_apis':
        { ... },
      'numberthree_apis':
        { ... }
    }