Download Report Files

The DCM/DFA Reporting and Trafficking API allows you to download report files, which are the result of running a Report Builder report. It also supports providing users direct access to a file via a link.

Depending on the type of download you'd like to perform, you'll use one of the following approaches:

The rest of this guide provides detailed instructions for performing these types of downloads via the Files resource.

Prerequisites

In order to download a file, you'll need a few pieces of information:

  1. The ID of the report to which the file belongs. You can find this by creating a new report, or looking up an existing report.
  2. The ID of the file to download. You can find this by running the report from the previous step, or querying the list of existing files as in the example below:

C#

File target = null;
FileList files;
String nextPageToken = null;

do {
  // Create and execute the files list request.
  ReportsResource.FilesResource.ListRequest request =
      service.Reports.Files.List(profileId, reportId);
  request.PageToken = nextPageToken;
  files = request.Execute();

  foreach (File file in files.Items) {
    if (IsTargetFile(file)) {
      target = file;
      break;
    }
  }

  // Update the next page token.
  nextPageToken = files.NextPageToken;
} while (target == null
    && files.Items.Any()
    && !String.IsNullOrEmpty(nextPageToken));

Java

File target = null;
FileList files;
String nextPageToken = null;

do {
  // Create and execute the files list request.
  files = reporting.reports().files().list(profileId, reportId).setPageToken(nextPageToken)
      .execute();

  for (File file : files.getItems()) {
    if (isTargetFile(file)) {
      target = file;
      break;
    }
  }

  // Update the next page token.
  nextPageToken = files.getNextPageToken();
} while (target == null
    && !files.getItems().isEmpty()
    && !Strings.isNullOrEmpty(nextPageToken));

PHP

$target = null;
$response = null;
$pageToken = null;

do {
  // Create and execute the file list request.
  $response = $this->service->reports_files->listReportsFiles(
      $userProfileId, $reportId, ['pageToken' => $pageToken]);

  foreach ($response->getItems() as $file) {
    if ($this->isTargetFile($file)) {
      $target = $file;
      break;
    }
  }

  $pageToken = $response->getNextPageToken();
} while (empty($target)
    && !empty($response->getItems())
    && !empty($pageToken));

Python

target = None

request = service.reports().files().list(
    profileId=profile_id, reportId=report_id)

while True:
  response = request.execute()

  for report_file in response['items']:
    if is_target_file(report_file):
      target = report_file
      break

  if not target and response['items'] and response['nextPageToken']:
    request = service.reports().files().list_next(request, response)
  else:
    break

Ruby

page_token = nil
target = nil

begin
  result = service.list_report_files(profile_id, report_id, {
    :page_token => page_token
  })

  result.items.each do |file|
    if is_target_file(file)
      target = file
      break
    end
  end

  if target.nil? and result.items.any?
    page_token = result.next_page_token
  else
    page_token = nil
  end
end until page_token.to_s.empty?

Note that the status field of the file resource must be set to REPORT_AVAILABLE to be eligible to download.

Direct download

To perform a direct download, you make an authorized HTTP GET request to the Files service and include the query parameter alt=media. An example request may look like this:

GET https://www.googleapis.com/dfareporting/v3.0/reports/12345/files/12345?alt=media HTTP/1.1
Authorization: Bearer your_auth_token

Be aware that the response you receive will contain a redirect, so your application should ideally be configured to handle this automatically. If you prefer to handle this manually, you can find the redirect URL in the Location header of the response.

Most of the official Google client libraries provide convenience methods for initiating a direct download, as shown in the example below. If you prefer to initiate a download manually, a pre-constructed URL is provided in the apiUrl field of the file resource.

C#

// Retrieve the file metadata.
File file = service.Files.Get(reportId, fileId).Execute();

if ("REPORT_AVAILABLE".Equals(file.Status)) {
  // Create a get request.
  FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId);

  // Optional: adjust the chunk size used when downloading the file.
  // getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize;

  // Execute the get request and download the file.
  using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file),
      System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
    getRequest.Download(outFile);
    Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name);
  }
}

Java

// Retrieve the file metadata.
File file = reporting.files().get(reportId, fileId).execute();

if ("REPORT_AVAILABLE".equals(file.getStatus())) {
  // Prepare a local file to download the report contents to.
  java.io.File outFile = new java.io.File(Files.createTempDir(), generateFileName(file));

  // Create a get request.
  Get getRequest = reporting.files().get(reportId, fileId);

  // Optional: adjust the chunk size used when downloading the file.
  // getRequest.getMediaHttpDownloader().setChunkSize(MediaHttpDownloader.MAXIMUM_CHUNK_SIZE);

  // Execute the get request and download the file.
  try (OutputStream stream = new FileOutputStream(outFile)) {
    getRequest.executeMediaAndDownloadTo(stream);
  }

  System.out.printf("File %d downloaded to %s%n", file.getId(), outFile.getAbsolutePath());
}

PHP

// Retrieve the file metadata.
$file = $this->service->files->get($reportId, $fileId);

if ($file->getStatus() === 'REPORT_AVAILABLE') {
  try {
    // Prepare a local file to download the report contents to.
    $fileName = join(DIRECTORY_SEPARATOR,
        [sys_get_temp_dir(), $this->generateFileName($file)]);
    $fileResource = fopen($fileName, 'w+');
    $fileStream = \GuzzleHttp\Psr7\stream_for($fileResource);

    // Execute the get request and download the file.
    $httpClient = $this->service->getClient()->authorize();
    $result = $httpClient->request('GET', $file->getUrls()->getApiUrl(), [
        \GuzzleHttp\RequestOptions::SINK => $fileStream
    ]);

    printf('<h3>Report file saved to: %s</h3>', $fileName);
  } finally {
    $fileStream->close();
    fclose($fileResource);
  }
}

Python

# Retrieve the file metadata.
report_file = service.files().get(
    reportId=report_id, fileId=file_id).execute()

if report_file['status'] == 'REPORT_AVAILABLE':
  # Prepare a local file to download the report contents to.
  out_file = io.FileIO(generate_file_name(report_file), mode='wb')

  # Create a get request.
  request = service.files().get_media(reportId=report_id, fileId=file_id)

  # Create a media downloader instance.
  # Optional: adjust the chunk size used when downloading the file.
  downloader = http.MediaIoBaseDownload(
      out_file, request, chunksize=CHUNK_SIZE)

  # Execute the get request and download the file.
  download_finished = False
  while download_finished is False:
    _, download_finished = downloader.next_chunk()

  print('File %s downloaded to %s' % (report_file['id'],
                                      os.path.realpath(out_file.name)))

Ruby

# Retrieve the file metadata.
report_file = service.get_file(report_id, file_id)

if report_file.status == 'REPORT_AVAILABLE'
  # Prepare a local file to download the report contents to.
  File.open(generate_file_name(report_file), 'w') do |out_file|
    # Execute the download request. Providing a download destination
    # retrieves the file contents rather than the file metadata.
    service.get_file(report_id, file_id, {:download_dest => out_file})

    puts 'File %s downloaded to %s' %
        [file_id, File.absolute_path(out_file.path)]
  end
end

Resumable downloads

When downloading large report files, it’s possible for the download to fail partway through. To make it easier to recover and resume a failed download, the file service supports partial download functionality.

Partial download involves requesting specific portions of a file, allowing you to break large downloads into smaller chunks. You can specify which portion of a file you want to download by including a byte range in the Range HTTP header of your request. For example:

Range: bytes=500-999

Partial download functionality is provided by many client libraries via a Media Download service. Refer to the client library documentation for details.

Download files in a browser

If you'd like to provide users with a way to download a file directly from their web browser, you can use the URL provided in the browserUrl field of the File resource. You can redirect a user to this URL, or offer it as a clickable link. In either case, the user will need to be logged into a Google account with access to DDM Reporting and have the correct permissions to access the specified file, in order to start the download.

C#

File file = service.Files.Get(reportId, fileId).Execute();
String browserUrl = file.Urls.BrowserUrl;

Java

File file = reporting.files().get(reportId, fileId).execute();
String browserUrl = file.getUrls().getBrowserUrl();

PHP

$file = $this->service->files->get($reportId, $fileId);
$browserUrl = $file->getUrls()->getBrowserUrl();

Python

report_file = service.files().get(
    reportId=report_id, fileId=file_id).execute()
browser_url = report_file['urls']['browserUrl']

Ruby

report_file = service.get_file(report_id, file_id)
browser_url = report_file.urls.browser_url

Send feedback about...

DoubleClick Campaign Manager
DoubleClick Campaign Manager