theGreatRegression
theGreatRegression

Reputation: 59

How do I capture JSON response from an API query into a separate output.json file when the below script runs ? #Beginner #Ruby

I would like to know how can I capture the JSON response that outputs once the above script runs and then create another file file.json where the JSON response is stored.

require "net/http"

url = URI("https://jakunamatata.net/v1/jakunamatata-analytics/summary")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Get.new(url)

response = https.request(request)
puts response.read_body;
// prints some json output

Upvotes: 0

Views: 108

Answers (1)

max
max

Reputation: 102250

require 'uri'
require 'pathname'
require 'net/http'

# This url does not seem to work - tested with example.com
url = URI("https://jakunamatata.net/v1/jakunamatata-analytics/summary")
path = Pathname.new(Dir.pwd).join('output.json')

Net::HTTP.start(url.host, url.port, use_ssl: true) do |http|
  request = Net::HTTP::Get.new(url)
  http.request(request) do |response|
    File.open(path, 'w') do |io|
      response.read_body do |chunk|
        io.write(chunk)
      end
    end
  end
end

puts "File downloaded to #{path}."

This streams the download directly to disk instead of reading the response body into memory. Once you get tired of reinventing the wheel checkout the down gem.

Upvotes: 1

Related Questions