Get file upload

Merchant API code sample to get file upload

AppsScript

// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


/**
 * Gets a File Upload Data Source
 */
function getFileUploadDataSource() {
  // IMPORTANT:
  // Enable the Merchant API DataSources Bundle Advanced Service and call it
  // "MerchantApiDataSources"

  // Replace this with your Merchant Center ID.
  const accountId = '<MERCHANT_CENTER_ID>';
  // Replace this with the ID of a File Upload Data Source.
  const dataSourceId = '<FILE_UPLOAD_DATA_SOURCE_ID>';
  // Construct the name. Use 'latest' alias to get the latest version of the File Upload
  const fileUploadName = 'accounts/' + accountId + '/dataSources/' + dataSourceId + "/fileUploads/latest";

  try {
    console.log('Sending get File Uploads request');
    // Call the DataSources.fileUploads.get API method.
    fileUpload =
        MerchantApiDataSources.Accounts.DataSources.FileUploads.get(fileUploadName);
    console.log(fileUpload);
  } catch (e) {
    console.log('ERROR!');
    console.log(e);
  }
}

Java

// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package shopping.merchant.samples.datasources.v1beta;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.FileUpload;
import com.google.shopping.merchant.datasources.v1beta.FileUploadName;
import com.google.shopping.merchant.datasources.v1beta.FileUploadsServiceClient;
import com.google.shopping.merchant.datasources.v1beta.FileUploadsServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.GetFileUploadRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to get the latest data source file upload. */
public class GetFileUploadSample {

  public static void getFileUpload(Config config, String datasourceId) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    FileUploadsServiceSettings fileUploadsServiceSettings =
        FileUploadsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates FileUpload name with datasource id to identify datasource.
    String name =
        FileUploadName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .setDatasource(datasourceId)
            .setFileupload("latest")
            .build()
            .toString();

    // Calls the API and catches and prints any network failures/errors.
    try (FileUploadsServiceClient fileUploadsServiceClient =
        FileUploadsServiceClient.create(fileUploadsServiceSettings)) {

      // The name has the format: accounts/{account}/datasources/{datasource}/fileUploads/latest
      GetFileUploadRequest request = GetFileUploadRequest.newBuilder().setName(name).build();

      System.out.println("Sending get FileUpload request:");
      FileUpload response = fileUploadsServiceClient.getFileUpload(request);

      System.out.println("Retrieved FileUpload below");
      System.out.println(response);
      //   return response;
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // An ID assigned to a datasource by Google.
    String datasourceId = "123456789";

    getFileUpload(config, datasourceId);
  }
}

PHP

<?php
/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../Authentication/Authentication.php';
require_once __DIR__ . '/../../Authentication/Config.php';
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\DataSources\V1beta\Client\FileUploadsServiceClient;
use Google\Shopping\Merchant\DataSources\V1beta\GetFileUploadRequest;

/**
 * This class demonstrates how to get the latest data source file upload.
 */
class GetFileUploadSample
{
    /**
     * Builds the full resource name for a file upload.
     *
     * @param string $accountId The Merchant Center account ID.
     * @param string $datasourceId The ID of the data source.
     * @return string The file upload name in the format:
     *      `accounts/{account}/datasources/{datasource}/fileUploads/latest`
     */
    private static function buildFileUploadName(string $accountId, string $datasourceId): string
    {
        // For this sample, we are always fetching the "latest" file upload.
        return sprintf(
            "accounts/%s/dataSources/%s/fileUploads/latest",
            $accountId,
            $datasourceId
        );
    }

    /**
     * Retrieves the latest file upload information for a specific data source.
     *
     * @param array $config Configuration array containing the Merchant Center account ID.
     * @param string $datasourceId The ID of the data source for which to retrieve
     *     the file upload.
     * @return void
     */
    public static function getFileUploadSample(array $config, string $datasourceId): void
    {
        // Obtains OAuth credentials from the service account or token file.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Configures the client options with the credentials.
        $options = ['credentials' => $credentials];

        // Creates a new FileUploadsServiceClient.
        $fileUploadsServiceClient = new FileUploadsServiceClient($options);

        // Constructs the full resource name for the file upload.
        // The name identifies the specific file upload to retrieve ("latest").
        $name = self::buildFileUploadName(
            $config['accountId'],
            $datasourceId
        );

        // Creates the GetFileUploadRequest.
        $request = new GetFileUploadRequest(['name' => $name]);

        // Calls the API to get the file upload information.
        try {
            print "Sending get FileUpload request:\n";
            $response = $fileUploadsServiceClient->getFileUpload($request);

            print "Retrieved FileUpload below\n";
            // Prints the retrieved FileUpload object as a JSON string.
            // This provides a comprehensive view of the response data.
            print $response->serializeToJsonString() . "\n";
        } catch (ApiException $e) {
            // Catches and prints any API errors.
            printf("ApiException was thrown: %s\n", $e->getMessage());
        }
    }

    /**
     * Helper function to execute the sample.
     *
     * @return void
     */
    public function callSample(): void
    {
        // Generates configuration details, including the account ID.
        $config = Config::generateConfig();

        // The ID of the data source, assigned by Google.
        // Replace with a valid datasource ID.
        $datasourceId = "<INSERT_DATA_SOURCE_ID>";

        // Calls the main sample function with the configuration and datasource ID.
        self::getFileUploadSample($config, $datasourceId);
    }
}

$sample = new GetFileUploadSample();
$sample->callSample();

Python

# -*- coding: utf-8 -*-
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""A module to get a FileUpload DataSource."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_datasources_v1beta import FileUploadsServiceClient
from google.shopping.merchant_datasources_v1beta import GetFileUploadRequest

# Fetches the Merchant Center account ID from the local configuration file.
# Ensure you have a valid configuration file for this to work.
_ACCOUNT_ID = configuration.Configuration().read_merchant_info()


def get_file_upload_sample(account_id: str, datasource_id: str) -> None:
  """Demonstrates how to get the latest data source file upload.

  Args:
    account_id: The Merchant Center account ID.
    datasource_id: The ID of the data source.
  """

  # Generates OAuth 2.0 credentials for authenticating with the API.
  credentials = generate_user_credentials.main()

  # Creates a FileUploadsServiceClient instance with the generated credentials.
  client = FileUploadsServiceClient(credentials=credentials)

  # Constructs the full resource name for the file upload.
  # The format is:
  # accounts/{account}/dataSources/{datasource}/fileUploads/latest
  name = f"accounts/{account_id}/dataSources/{datasource_id}/fileUploads/latest"

  # Creates a request to get the specified file upload.
  request = GetFileUploadRequest(name=name)

  print("Sending get FileUpload request:")
  try:
    # Makes the API call to retrieve the file upload information.
    response = client.get_file_upload(request=request)

    print("Retrieved FileUpload below")
    print(response)
  except RuntimeError as e:
    # Catches and prints any errors that occur during the API call.
    print(e)


if __name__ == "__main__":
  # The ID of the datasource for which to retrieve the latest file upload.
  # This is a placeholder ID. Replace with a valid datasource ID.
  datasource_id_to_get = "<INSERT_DATASOURCE_ID>"

  get_file_upload_sample(_ACCOUNT_ID, datasource_id_to_get)