Ruby Screenshot API code sample

Tested on Ruby 2.3

require "net/http"
require "net/https"
require "uri"
require "json"

API_KEY = "YOUR API KEY GOES HERE"

def beginCapture(url,viewport,fullpage,webdriver,javascript)
  serverUrl = "https://api.screenshotapi.io/capture"
  puts "Sending request: #{serverUrl}"
  uri = URI.parse(serverUrl)
  https = Net::HTTP.new(uri.host,uri.port)
  https.use_ssl = true
  req = Net::HTTP::Post.new(serverUrl, initheader = {'apikey' => API_KEY})
  req.set_form_data({"url" => url, "viewport" => viewport, "fullpage" => fullpage, "webdriver" => webdriver, "javascript" => javascript})

  result = https.request(req)
  #{"status":"ready","key":"f469a4c54b4852b046c6f210935679ae"}
  json_results = JSON.parse(result.body)
  key = json_results["key"]
  puts "Capture request key is #{key}"
  return key
end

RetrieveResult = Struct.new(:success, :bytes)

def tryRetrieve(key)
  serverUrl = "https://api.screenshotapi.io/retrieve?key=" + key
  puts "Trying to retrieve: " + serverUrl

  uri = URI.parse(serverUrl)
  https = Net::HTTP.new(uri.host,uri.port)
  https.use_ssl = true
  req = Net::HTTP::Get.new(serverUrl, initheader = {'apikey' => API_KEY})
  result = https.request(req)
  json_results = JSON.parse(result.body)
  #{ "status":"ready","imageUrl":"http://screenshotapi.s3.amazonaws.com/captures/f469a4c54b4852b046c6f210935679ae.png"}
  retResult =  RetrieveResult.new

  if json_results["status"] == "ready"
    puts "Downloading image: " + json_results["imageUrl"]
    retResult.success = true
    image_result = Net::HTTP.get_response(URI.parse(json_results["imageUrl"]))
    retResult.bytes =  image_result.body
  else
    retResult.success = false
  end

  return retResult
end


key = beginCapture("http://www.amazon.com","1200x800","true","firefox","true")

timeout = 30
tCounter = 0
tCountIncr = 3

while true do
  retResult = tryRetrieve(key)
  if retResult.success
    puts "Saving screenshot to downloaded_screenshot.png"
    outfile = File.new('downloaded_screenshot.png', 'w')
    outfile.puts(retResult.bytes)
    outfile.close
    break
  else
    tCounter += tCountIncr
    puts "Screenshot not yet ready.. waiting for: " + tCountIncr.to_s + " seconds."
    sleep(tCountIncr)
    if tCounter > timeout
      puts "Timed out while trying to retrieve: " + key
      break
    end
  end
end