Merchant API code sample to fetch file data source
Java
// 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.
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.DataSourceName;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.FetchDataSourceRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/**
* This class demonstrates how to fetch a specific FileInput DataSource for a given Merchant Center
* account.
*/
public class FetchFileDataSourceSample {
public static void fetchDataSource(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.
DataSourcesServiceSettings dataSourcesServiceSettings =
DataSourcesServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates datasource name to identify datasource.
String name =
DataSourceName.newBuilder()
.setAccount(config.getAccountId().toString())
.setDatasource(dataSourceId)
.build()
.toString();
// Calls the API and catches and prints any network failures/errors.
try (DataSourcesServiceClient dataSourcesServiceClient =
DataSourcesServiceClient.create(dataSourcesServiceSettings)) {
// The name has the format: accounts/{account}/datasources/{datasource}
FetchDataSourceRequest request = FetchDataSourceRequest.newBuilder().setName(name).build();
System.out.println("Sending FETCH DataSource request:");
// Fetch works ONLY for FileInput DataSource type.
dataSourcesServiceClient.fetchDataSource(request); // No response returned on success
System.out.println("Successfully fetched DataSource.");
} catch (Exception e) {
System.out.println(e);
System.exit(1);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
String datasourceId = "<DATASOURCE_ID>"; // Replace with your FileInput DataSource ID.
fetchDataSource(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\DataSourcesServiceClient;
use Google\Shopping\Merchant\DataSources\V1beta\FetchDataSourceRequest;
/**
* This class demonstrates how to fetch a specific FileInput DataSource for a given Merchant Center
* account.
*/
class FetchFileDataSourceSample
{
/**
* Helper function to construct the full data source resource name.
*
* @param string $accountId The Merchant Center account ID.
* @param string $dataSourceId The data source ID.
* @return string The formatted data source name.
*/
private static function buildDataSourceName(string $accountId, string $dataSourceId): string
{
return sprintf("accounts/%s/dataSources/%s", $accountId, $dataSourceId);
}
/**
* Fetches a specific FileInput DataSource.
*
* @param array $config The configuration array containing the account ID.
* @param string $dataSourceId The ID of the FileInput DataSource to fetch.
*/
public static function fetchDataSource(array $config, string $dataSourceId): void
{
// Obtains OAuth token based on the user's configuration.
$credentials = Authentication::useServiceAccountOrTokenFile();
// Creates service client configuration object using the credentials.
$options = ['credentials' => $credentials];
// Creates a DataSourcesServiceClient with the specified options.
$dataSourcesServiceClient = new DataSourcesServiceClient($options);
// Constructs the full resource name for the data source.
// The name has the format: accounts/{account}/datasources/{datasource}
$name = self::buildDataSourceName($config['accountId'], $dataSourceId);
// Creates the request to fetch the data source.
$request = new FetchDataSourceRequest(['name' => $name]);
// Calls the API and handles potential errors.
try {
print "Sending FETCH DataSource request:\n";
// The fetchDataSource method does not return a response body on success.
// It will throw an ApiException if the fetch fails or the data source is not found.
// This operation works ONLY for FileInput DataSource types.
$dataSourcesServiceClient->fetchDataSource($request);
print "Successfully fetched DataSource.\n";
} catch (ApiException $e) {
printf("ApiException was thrown: %s\n", $e->getMessage());
}
}
/**
* Executes the sample code.
*/
public function callSample(): void
{
$config = Config::generateConfig();
// ENSURE you fill in the datasource ID for the sample to work.
// This ID should correspond to a FileInput DataSource.
$dataSourceId = '10432397780';
// Calls the method to fetch the data source.
self::fetchDataSource($config, $dataSourceId);
}
}
$sample = new FetchFileDataSourceSample();
$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.
"""Sample for fetching a FileInput DataSource."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_datasources_v1beta import DataSourcesServiceClient
from google.shopping.merchant_datasources_v1beta import FetchDataSourceRequest
# Read the Merchant Center account ID from the configuration file.
# This ID is used to identify the account under which the data source operation
# will be performed.
_ACCOUNT_ID = configuration.Configuration().read_merchant_info()
def fetch_file_data_source(datasource_id: str):
"""Fetches a specific FileInput DataSource for the configured Merchant Center account.
This operation is specific to DataSources of type FileInput. Attempting to
fetch other types of DataSources will result in an API error.
Args:
datasource_id: The unique identifier of the data source to fetch.
"""
# Obtain OAuth 2.0 credentials for authenticating API requests.
credentials = generate_user_credentials.main()
# Create an instance of the DataSourcesServiceClient using the obtained
# credentials. This client is used to interact with the Merchant API's
# DataSources service.
client = DataSourcesServiceClient(credentials=credentials)
# Construct the full resource name for the data source.
# The format is `accounts/{account_id}/dataSources/{datasource_id}`.
name = f"accounts/{_ACCOUNT_ID}/dataSources/{datasource_id}"
# Create a FetchDataSourceRequest object, setting the name of the data source
# to be fetched.
request = FetchDataSourceRequest(name=name)
# Inform the user that the fetch request is being sent.
print("Sending FETCH DataSource request:")
# Execute the fetch_data_source API call.
try:
# For FileInput DataSources, a successful fetch operation does not return
# any data in the response body. The call's success implies the fetch was
# triggered. If the API call encounters an error (e.g., DataSource not
# found, network issue, or if the DataSource is not a FileInput type), a
# RuntimeError will be raised.
client.fetch_data_source(request=request)
print("Successfully fetched DataSource.")
except RuntimeError as e:
# If an error occurs during the API call, print the error details.
print(e)
if __name__ == "__main__":
# The ID of the FileInput DataSource that needs to be fetched.
# IMPORTANT: You must replace "<DATASOURCE_ID>" with a valid DataSource ID
# that corresponds to a FileInput type DataSource in your Merchant Center
# account.
datasource_id_to_fetch = "<DATASOURCE_ID>"
fetch_file_data_source(datasource_id=datasource_id_to_fetch)