GitHub 上的 googleads/googleads-shopping-samples 代码库包含每个客户端库的常见操作示例代码。例如,googleads-shopping-samples/python/shopping/content/products/ 中的示例提供了使用 Python 与 products
资源执行常见操作的代码。在本指南中,您将从一个空文件开始,构建一个用于插入新商品的示例,以便了解与 Content API 集成的应用的基本结构和必需组件。最终结果将类似于 products/insert.py 示例文件中的示例。然后,您可以使用 products.list
方法的 API Explorer 来验证产品是否已成功添加。
如需进行首次通话,请完成以下步骤:
在 googleads-shopping-samples/python/shopping/content/products/ 目录中,创建一个空的 my-insert.py 文件。将以下步骤中的所有代码添加到此文件中。
为所需的模块添加导入语句。
在 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
如果调用成功,服务会向终端输出以下消息:创建了 offerId 为“offerId”的商品。
如需验证商品是否已成功添加,请使用 API Explorer 中的
products.list
方法返回 Merchant Center 账号中的所有商品。在
products.list
方法的 API Explorer 中,输入以下值:- 输入您的
merchantId
。
- 在凭据部分中,选择 Google OAuth 2.0 和 API 密钥。
- 点击执行按钮。
- 如果系统提示,请使用与您的 Merchant Center 账号关联的 Google 账号登录。
如果商品成功添加,商品数据会显示在 API Explorer 响应中。
- 输入您的
商家有责任遵守购物广告和非付费商品详情政策。Google 购物保留强制执行这些政策的权利,如果发现违反这些政策的内容或行为,将会采取适当措施。