googleads / googleads-dfa-reporting-samples

Samples for the DoubleClick for Advertisers Reporting and Trafficking API
Apache License 2.0
106 stars 173 forks source link

Ruby Version for downloading the Reports #2

Closed sebaas closed 10 years ago

sebaas commented 10 years ago

In the download_file.rb:

def download_file(dfareporting, args)
  # Get all reports
  result = dfareporting.files.get(
    :alt => 'media',
    :reportId => args['report_id'],
    :fileId => args['file_id']
  ).execute()

  # Files.get returns a redirect to the actual report file
  real_url = result.headers['location']

  # Obtain the file and display results.
  puts Faraday.get(real_url).body
end

You add :alt => 'media' that makes the result to have 301 redirection status. And from the headers (result.headers['location']) you capture the redirection URL and download the correct file.

If I remove the alt param from the request. The answer status is 200 and the answer has:

{
 "kind": "dfareporting#file",
 "etag": "\"-----------------------------------------\"",
 "reportId": "-----------",
 "id": "-----------",
 "lastModifiedTime": "1406318594641",
 "status": "REPORT_AVAILABLE",
 "fileName": "test-total-conversions",
 "format": "CSV",
 "dateRange": {
  "kind": "dfareporting#dateRange",
  "startDate": "2013-07-25",
  "endDate": "2014-07-24"
 },
 "urls": {
  "browserUrl": "https://www.google.com/analytics/dfa/downloadFile?id=-----------:-------------",
  "apiUrl": "https://www.googleapis.com/dfareporting/v1.3/reports/---------/files/-----------?alt=media"
 }
}

However I couldn't get the apiUrl to work with Faraday as it returns me that I'm not logged in.

jimper commented 10 years ago

If you take a look at the reference docs for Reports.files.get, you'll see that the alt parameter controls whether the response is JSON metadata or the actual contents of the file. Since we want to download the file in this example, setting :alt => 'media' is the preferred method.

In reality, when using this param, the response is a redirect to the actual file. Unfortunately, the Google APIs client library for Ruby doesn't like to automatically follow redirects, which led to the workaround above. If/when the library is patched to handle redirects, this example will be updated accordingly.

Note: to use the apiUrl returned in your example requires an OAuth 2.0 authorization header be set in the request. You'll need to set this into the request manually if you're using Faraday directly.