یک منبع داده دریافت کنید
با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
نمونه کد API Merchant برای دریافت منبع داده.
جاوا
// 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.v1;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1.DataSource;
import com.google.shopping.merchant.datasources.v1.DataSourceName;
import com.google.shopping.merchant.datasources.v1.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1.GetDataSourceRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to get a specific datasource for a given Merchant Center account. */
public class GetDataSourceSample {
public static DataSource getDataSource(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}
GetDataSourceRequest request = GetDataSourceRequest.newBuilder().setName(name).build();
System.out.println("Sending GET DataSource request:");
DataSource response = dataSourcesServiceClient.getDataSource(request);
System.out.println("Retrieved DataSource below");
System.out.println(response);
return response;
} catch (Exception e) {
System.out.println(e);
System.exit(1);
return null; // Necessary to satisfy the compiler as we're not returning a
// DataSource on failure.
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
// An ID assigned to a datasource by Google.
String datasourceId = "1111111111"; // Replace with your datasource ID.
getDataSource(config, datasourceId);
}
}
PHP
<?php
/**
* 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.
*/
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\V1\Client\DataSourcesServiceClient;
use Google\Shopping\Merchant\DataSources\V1\DataSource;
use Google\Shopping\Merchant\DataSources\V1\GetDataSourceRequest;
/**
* Class to demonstrate getting a specific datasource for a given Merchant
* Center account.
*/
class GetDataSourceSample
{
// ENSURE you fill in the datasource ID for the sample to work.
private const DATASOURCE_ID = 'INSERT_DATASOURCE_ID';
/**
* Gets a DataSource.
*
* @param int $merchantId The Merchant Center Account ID.
* @param string $dataSourceId The data source ID.
* @return DataSource The retrieved data source.
*/
public function getDataSource(int $merchantId, string $dataSourceId): DataSource
{
// Gets the OAuth credentials to make the request.
$credentials = Authentication::useServiceAccountOrTokenFile();
// Creates options config containing credentials for the client to use.
$options = ['credentials' => $credentials];
// Creates a client.
$dataSourcesServiceClient = new DataSourcesServiceClient($options);
// Creates the data source name.
$name = sprintf('accounts/%s/dataSources/%s', $merchantId, $dataSourceId);
// Creates the request.
$request = (new GetDataSourceRequest())
->setName($name);
print('Sending GET DataSource request:' . PHP_EOL);
// Calls the API and catches and prints any network failures/errors.
try {
$response = $dataSourcesServiceClient->getDataSource($request);
print('Retrieved DataSource below' . PHP_EOL);
print($response->serializeToJsonString() . PHP_EOL);
return $response;
} catch (ApiException $ex) {
print('Call failed with message: ' . $ex->getMessage() . PHP_EOL);
return new DataSource();
}
}
// Helper to execute the sample.
public function callSample(): void
{
$config = Config::generateConfig();
// The Merchant Center Account ID.
$merchantId = $config['accountId'];
self::getDataSource($merchantId, self::DATASOURCE_ID);
}
}
$sample = new GetDataSourceSample();
$sample->callSample();
پایتون
# -*- coding: utf-8 -*-
# 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
#
# 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 DataSource."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_datasources_v1
# ENSURE you fill in the datasource ID for the sample to
# work.
_ACCOUNT = configuration.Configuration().read_merchant_info()
_DATASOURCE = "[INSERT_DATASOURCE_HERE]"
_NAME = f"accounts/{_ACCOUNT}/dataSources/{_DATASOURCE}"
def get_data_source():
"""Gets the specified `DataSource` resource."""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = merchant_datasources_v1.DataSourcesServiceClient(
credentials=credentials
)
# Creates the request.
request = merchant_datasources_v1.GetDataSourceRequest(name=_NAME)
# Makes the request and catch and print any error messages.
try:
response = client.get_data_source(request=request)
print(f"Get successful: {response}")
except RuntimeError as e:
print("Get failed")
print(e)
if __name__ == "__main__":
get_data_source()
جز در مواردی که غیر از این ذکر شده باشد،محتوای این صفحه تحت مجوز Creative Commons Attribution 4.0 License است. نمونه کدها نیز دارای مجوز Apache 2.0 License است. برای اطلاع از جزئیات، به خطمشیهای سایت Google Developers مراجعه کنید. جاوا علامت تجاری ثبتشده Oracle و/یا شرکتهای وابسته به آن است.
تاریخ آخرین بهروزرسانی 2025-08-21 بهوقت ساعت هماهنگ جهانی.
[null,null,["تاریخ آخرین بهروزرسانی 2025-08-21 بهوقت ساعت هماهنگ جهانی."],[[["\u003cp\u003eThis webpage provides code samples in Java, PHP, and Python demonstrating how to retrieve a specific data source from a Google Merchant Center account using the Merchant API.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples require OAuth credentials for authentication to interact with the Merchant API and need to be configured with the specific Merchant Center account ID and data source ID.\u003c/p\u003e\n"],["\u003cp\u003eThe Java sample shows how to create a service client and make an API call to get a data source, while the PHP and Python examples illustrate a similar process tailored to their respective language and library.\u003c/p\u003e\n"],["\u003cp\u003eEach code example uses a \u003ccode\u003eGetDataSourceRequest\u003c/code\u003e to specify the data source to retrieve, and handles API responses and potential errors.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code is licensed under the Apache License, Version 2.0, offering flexibility in usage and modification, and is retrievable in the specified github links.\u003c/p\u003e\n"]]],["The provided code samples demonstrate how to retrieve a specific data source from a Merchant Center account using Java, PHP, and Python. The core actions involve authenticating with OAuth, creating a service client, constructing a data source name from account and data source IDs, building a `GetDataSourceRequest`, and sending this request to the API. The API call returns a `DataSource` object, which is then printed to the console, if there are no errors. Each code snippet requires an account and datasource id.\n"],null,["# Get a data source\n\nMerchant API code sample to get a data source. \n\n### Java\n\n // Copyright 2024 Google LLC\n //\n // Licensed under the Apache License, Version 2.0 (the \"License\");\n // you may not use this file except in compliance with the License.\n // You may obtain a copy of the License at\n //\n // https://www.apache.org/licenses/LICENSE-2.0\n //\n // Unless required by applicable law or agreed to in writing, software\n // distributed under the License is distributed on an \"AS IS\" BASIS,\n // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n // See the License for the specific language governing permissions and\n // limitations under the License.\n\n package shopping.merchant.samples.datasources.v1;\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.datasources.v1.DataSource;\n import com.google.shopping.merchant.datasources.v1.DataSourceName;\n import com.google.shopping.merchant.datasources.v1.DataSourcesServiceClient;\n import com.google.shopping.merchant.datasources.v1.DataSourcesServiceSettings;\n import com.google.shopping.merchant.datasources.v1.GetDataSourceRequest;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to get a specific datasource for a given Merchant Center account. */\n public class GetDataSourceSample {\n\n public static DataSource getDataSource(Config config, String dataSourceId) throws Exception {\n\n // Obtains OAuth token based on the user's configuration.\n GoogleCredentials credential = new Authenticator().authenticate();\n\n // Creates service settings using the credentials retrieved above.\n DataSourcesServiceSettings dataSourcesServiceSettings =\n DataSourcesServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n // Creates datasource name to identify datasource.\n String name =\n DataSourceName.newBuilder()\n .setAccount(config.getAccountId().toString())\n .setDatasource(dataSourceId)\n .build()\n .toString();\n\n // Calls the API and catches and prints any network failures/errors.\n try (DataSourcesServiceClient dataSourcesServiceClient =\n DataSourcesServiceClient.create(dataSourcesServiceSettings)) {\n\n // The name has the format: accounts/{account}/datasources/{datasource}\n GetDataSourceRequest request = GetDataSourceRequest.newBuilder().setName(name).build();\n\n System.out.println(\"Sending GET DataSource request:\");\n DataSource response = dataSourcesServiceClient.getDataSource(request);\n\n System.out.println(\"Retrieved DataSource below\");\n System.out.println(response);\n return response;\n } catch (Exception e) {\n System.out.println(e);\n System.exit(1);\n return null; // Necessary to satisfy the compiler as we're not returning a\n // DataSource on failure.\n }\n }\n\n public static void main(String[] args) throws Exception {\n Config config = Config.load();\n // An ID assigned to a datasource by Google.\n String datasourceId = \"1111111111\"; // Replace with your datasource ID.\n\n getDataSource(config, datasourceId);\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/datasources/v1/GetDataSourceSample.java\n\n### PHP\n\n \u003c?php\n /**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n require_once __DIR__ . '/../../../vendor/autoload.php';\n require_once __DIR__ . '/../../Authentication/Authentication.php';\n require_once __DIR__ . '/../../Authentication/Config.php';\n use Google\\ApiCore\\ApiException;\n use Google\\Shopping\\Merchant\\DataSources\\V1\\Client\\DataSourcesServiceClient;\n use Google\\Shopping\\Merchant\\DataSources\\V1\\DataSource;\n use Google\\Shopping\\Merchant\\DataSources\\V1\\GetDataSourceRequest;\n\n /**\n * Class to demonstrate getting a specific datasource for a given Merchant\n * Center account.\n */\n class GetDataSourceSample\n {\n // ENSURE you fill in the datasource ID for the sample to work.\n private const DATASOURCE_ID = 'INSERT_DATASOURCE_ID';\n\n /**\n * Gets a DataSource.\n *\n * @param int $merchantId The Merchant Center Account ID.\n * @param string $dataSourceId The data source ID.\n * @return DataSource The retrieved data source.\n */\n public function getDataSource(int $merchantId, string $dataSourceId): DataSource\n {\n // Gets the OAuth credentials to make the request.\n $credentials = Authentication::useServiceAccountOrTokenFile();\n\n // Creates options config containing credentials for the client to use.\n $options = ['credentials' =\u003e $credentials];\n\n // Creates a client.\n $dataSourcesServiceClient = new DataSourcesServiceClient($options);\n\n // Creates the data source name.\n $name = sprintf('accounts/%s/dataSources/%s', $merchantId, $dataSourceId);\n\n // Creates the request.\n $request = (new GetDataSourceRequest())\n -\u003esetName($name);\n\n print('Sending GET DataSource request:' . PHP_EOL);\n\n // Calls the API and catches and prints any network failures/errors.\n try {\n $response = $dataSourcesServiceClient-\u003egetDataSource($request);\n print('Retrieved DataSource below' . PHP_EOL);\n print($response-\u003eserializeToJsonString() . PHP_EOL);\n return $response;\n } catch (ApiException $ex) {\n print('Call failed with message: ' . $ex-\u003egetMessage() . PHP_EOL);\n return new DataSource();\n }\n }\n\n // Helper to execute the sample.\n public function callSample(): void\n {\n $config = Config::generateConfig();\n // The Merchant Center Account ID.\n $merchantId = $config['accountId'];\n\n self::getDataSource($merchantId, self::DATASOURCE_ID);\n }\n }\n\n $sample = new GetDataSourceSample();\n $sample-\u003ecallSample(); \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/php/examples/datasources/v1/GetDataSourceSample.php\n\n### Python\n\n # -*- coding: utf-8 -*-\n # Copyright 2024 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \"\"\"A module to get a DataSource.\"\"\"\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping import merchant_datasources_v1\n\n # ENSURE you fill in the datasource ID for the sample to\n # work.\n _ACCOUNT = configuration.Configuration().read_merchant_info()\n _DATASOURCE = \"[INSERT_DATASOURCE_HERE]\"\n _NAME = f\"accounts/{_ACCOUNT}/dataSources/{_DATASOURCE}\"\n\n\n def get_data_source():\n \"\"\"Gets the specified `DataSource` resource.\"\"\"\n\n # Gets OAuth Credentials.\n credentials = generate_user_credentials.main()\n\n # Creates a client.\n client = merchant_datasources_v1.DataSourcesServiceClient(\n credentials=credentials\n )\n\n # Creates the request.\n request = merchant_datasources_v1.GetDataSourceRequest(name=_NAME)\n\n # Makes the request and catch and print any error messages.\n try:\n response = client.get_data_source(request=request)\n print(f\"Get successful: {response}\")\n except RuntimeError as e:\n print(\"Get failed\")\n print(e)\n\n\n if __name__ == \"__main__\":\n get_data_source()\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/datasources/v1/get_data_source_sample.py"]]