GitHub 上的 googleads/googleads-shopping-samples 代码库包含每个客户端库常见操作的示例代码。例如,googleads-shopping-samples/python/shopping/content/products/ 中的示例提供了在 Python 中使用 products
资源的常见操作代码。在本指南中,您将从一个空文件入手,构建一个用于插入新产品的示例,以便查看与 Content API 集成的应用的基本结构和必需组件。最终结果与 products/insert.py 示例文件中的示例类似。然后,您可以使用 API Explorer 中的 products.list
方法验证商品是否已成功添加。
要进行首次调用,请完成以下步骤:
在 googleads-shopping-samples/python/shopping/content/products/ 目录中,创建一个空的 my-insert.py 文件。将以下步骤中的所有代码添加到此文件中。
为所需模块添加 import 语句。
在 my-insert.py 的开头添加以下代码:
from __future__ import print_function import sys # The common module provides setup functionality used by the samples, # such as authentication and unique id generation. from shopping.content import common
定义唯一商品 ID 并创建包含商品定义的字典。
在 my-insert.py 的末尾,添加以下代码:
offer_id = 'book#%s' % common.get_unique_id() product = { 'offerId': offer_id, 'title': 'A Tale of Two Cities', 'description': 'A classic novel about the French Revolution', 'link': 'http://my-book-shop.com/tale-of-two-cities.html', 'imageLink': 'http://my-book-shop.com/tale-of-two-cities.jpg', 'contentLanguage': 'en', 'targetCountry': 'US', 'channel': 'online', 'availability': 'in stock', 'condition': 'new', 'googleProductCategory': 'Media > Books', 'gtin': '9780007350896', 'price': { 'value': '2.50', 'currency': 'USD' }, 'shipping': [{ 'country': 'US', 'service': 'Standard shipping', 'price': { 'value': '0.99', 'currency': 'USD' } }], 'shippingWeight': { 'value': '200', 'unit': 'grams' } }
创建一个从命令行运行脚本时运行的函数。该函数会构建一个与 Content API 交互的服务对象,从配置文件中获取商家 ID,构建请求,并执行请求以发出 API 调用。
在 my-insert.py 的末尾,添加以下代码:
def main(argv): # Construct the service object to interact with the Content API. service, config, _ = common.init(argv, __doc__) # Get the merchant ID from merchant-info.json. merchant_id = config['merchantId'] # Create the request with the merchant ID and product object. request = service.products().insert(merchantId=merchant_id, body=product) # Execute the request and print the result. result = request.execute() print('Product with offerId "%s" was created.' % (result['offerId'])) # Allow the function to be called with arguments passed from the command line. if __name__ == '__main__': main(sys.argv)
要运行脚本并执行 API 调用,请在终端窗口中转到 googleads-shopping-samples/python/,然后运行以下命令:
python -m shopping.content.products.my-insert
如果调用成功,服务会将以下消息输出到终端:Product with offerId "offerId" was created.
如需验证商品是否已成功添加,请使用 API Explorer 中的
products.list
方法返回 Merchant Center 账号中的所有商品。在 API Explorer 中的
products.list
方法中,输入以下值:- 输入您的
merchantId
。
- 在凭据部分中,选择 Google OAuth 2.0 和 API 密钥。
- 点击执行按钮。
- 如果系统提示,请使用与您的 Merchant Center 帐号关联的 Google 帐号登录。
如果商品添加成功,则商品数据会显示在 API Explorer 响应中。
- 输入您的
商家有责任遵守购物广告和非付费商品详情政策。Google 购物有权执行这些政策,并在发现违反这些政策的内容或行为时做出适当回应。