How to Save File using Ruby 2.2.3 and rest-client
Asked Answered
S

2

5

I am trying to use a rest API to download a file, it appears to work, but I dont actually have a file downloaded. I am assuming its because its going to memory, and not to my file system.

Below is the portion of code responsible. My URL is slightly edited when pasting it below, and my authToken is valid.

backup_url = "#{proto}://#{my_host}/applications/ws/migration/export?noaudit=#{include_audit}&includebackup=#{include_backup_zips}&authToken=#{my_token}"
resource = RestClient::Resource.new(
  backup_url,
  :timeout => nil,
  :open_timeout => nil)
response = resource.get
if response.code == 200
    puts "Backup Complete"
else
    puts "Backup Failed"
    abort("Response Code was not 200: Response Code #{response.code}")
end

Returns:

# => 200 OK | application/zip 222094570 bytes
Backup Complete

There is no file present though.

Thanks,

Syngamy answered 7/12, 2015 at 18:3 Comment(0)
H
8

Well you actually have to write to the file yourself.

Pathname('backup.zip').write response.to_s
Homothermal answered 7/12, 2015 at 18:9 Comment(2)
Where would this be placed?Syngamy
You should try browsing through the docs. It's really more efficient than asking for everything. You'll find Dir.getwd, which gives you the current working directory. Alternatively, specify an absolute path in File.write. Oh, you meant where the File.write line should be placed? Right before puts "Backup complete"Homothermal
G
2

You can save the zip file using File class

...
if response.code == 200
    f = File.new("backup.zip", "wb")
    f << response.body
    f.close
    puts "Backup Complete"
else 
...
Gallardo answered 7/12, 2015 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.