Ads Data Hub API 使用入门

本指南介绍如何着手编写使用 Ads Data Hub REST API 与广告数据中心进行交互的应用。通过 Ads Data Hub REST API,您可以查看与您的 Google 账号相关联的广告数据中心客户、创建查询以及运行查询。

设置

在使用 Ads Data Hub API 之前,您需要完成以下几个步骤:

  1. 确保在 Google Cloud 项目中向启用 API 的用户授予 serviceusage.services.enable 权限。还必须将具有 serviceusage.services.enable 权限的用户列入许可名单,他们才能访问该 API。
  2. 在创建客户端凭据服务账号的 Google Cloud 项目中启用 Ads Data Hub API。使用控制台为某个项目启用 Ads Data Hub API 的步骤如下:
    1. 前往 Cloud Console API 库
    2. 从项目列表中选择想要使用的项目。
    3. 搜索“Ads Data Hub API”。
    4. 在 API 页面上,点击启用
  3. 管理权限:
    1. 必须将创建凭据时所使用的电子邮件地址或服务账号添加到广告数据中心,并授予适当的权限。对于服务账号而言,这是指该服务账号的电子邮件地址。对于 OAuth 而言,这是指该用户的电子邮件地址。这样可以确保服务账号或最终用户的账号具有在广告数据中心内运行查询的权限。
  4. (推荐)安装 Google API 客户端库
    1. Google API 客户端库提供多种主流语言版本。通过该客户端库,您可以使用多种 Google API。虽然这不是强制性的要求,但客户端库可减少您需要编写的代码量,并简化身份验证的设置。
客户端库 广告数据中心示例
适用于 Java 的 Google API 客户端库 Java
适用于 Python 的 Google API 客户端库

身份验证和授权

Ads Data Hub API 可访问和更改您的广告数据中心客户账号内的数据,因此它需要确保您是已获授权的用户。鉴于此,在开始与 Ads Data Hub API 交互之前,需要完成授权流程。完成授权流程后,您便可获得与该 API 交互的必要权限。您可以使用 OAuth 2.0 或服务账号进行身份验证。

OAuth 2.0 设置

该 API 既支持已安装应用流程,也支持 Web 应用流程。但在此示例中,我们将逐步介绍已安装应用流程。

  1. 前往 Google API 控制台并找到您的管理项目。
  2. 确认是否为该项目启用了 Ads Data Hub API。
    1. 如果未启用,请点击“+ 启用 API 和服务”,以将其启用。
  3. 在左侧导航栏中,点击“凭据”。
  4. 打开“创建凭据”下拉菜单,然后选择“OAuth 客户端 ID”。在接下来的页面上:
    1. 选择“其他”。
    2. (可选)为客户端命名。
    3. 点击“创建”。
  5. 点击您刚才创建的凭据旁边的下载图标。

获取 API 密钥

在下面的 Python 代码示例中,将使用您的 API 密钥(也称为开发者密钥)进行身份验证。获取 API 密钥的步骤如下:

  1. 前往 API 控制台的“凭据”页面。
  2. 确保在顶部导航栏的下拉菜单中选中您的管理项目。
  3. 点击您的 API 密钥旁边的下载图标。

发送示例请求

Python

"""This sample shows how to retrieve all accounts associated with the user.

For the program to execute successfully, ensure that you run it using Python 3.
"""
import json
from google_auth_oauthlib import flow
from googleapiclient.discovery import build

appflow = flow.InstalledAppFlow.from_client_secrets_file(
    # Replace client_secrets.json with your own client secret file.
    'client_secrets.json',
    scopes=['https://www.googleapis.com/auth/adsdatahub'])
appflow.run_local_server()
credentials = appflow.credentials
developer_key = input('Developer key: ').strip()
# For versions of the Google API Python client library prior to 2.0, the
# `static_discovery` parameter below should be removed.
service = build('AdsDataHub', 'v1', credentials=credentials,
                developerKey=developer_key, static_discovery=False)


def pprint(x):
  print(json.dumps(x, sort_keys=True, indent=4))


adh_account_id = input('ADH account ID (e.g. "customers/123456789"): ').strip()
pprint(service.customers().analysisQueries().list(parent
                                                  =adh_account_id).execute())

      

Java

/*
 * Copyright (c) 2019 Google Inc.
 *
 * 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.
 */

package com.google.api.services.samples.adsdatahub.cmdline;

import com.google.api.services.adsdatahub.v1.AdsDataHub;
import com.google.api.services.adsdatahub.v1.model.Customer;
import com.google.api.services.adsdatahub.v1.model.ListCustomersResponse;
import java.io.IOException;
import java.util.List;

/**
 * This sample illustrates how to retrieve all accounts associated to the user.
 *
 * <p>See the <a href="customers.list reference
 * documentation">https://developers.google.com/ads-data-hub/reference/rest/v1/customers/list</a>
 * for more details.
 */
public class ListCustomers extends BaseSample {

  @Override
  public String getName() {
    return "List customers";
  }

  @Override
  public String getDescription() {
    return "Lists customers associated with the authorized user";
  }

  @Override
  public void execute(AdsDataHub client) throws IOException {
    String pageToken = null;
    boolean noData = true;

    System.out.println("========================================");
    System.out.printf("Listing of customers associated with the authorized user:\n");
    System.out.println("========================================");

    do {
      ListCustomersResponse response = client.customers().list().setPageToken(pageToken).execute();
      pageToken = response.getNextPageToken();
      List<Customer> customers = response.getCustomers();

      if (customers != null && customers.size() > 0) {
        noData = false;
        for (Customer customer : customers) {
          System.out.printf("* Customer id: %d\n", customer.getCustomerId());
          System.out.printf("\tCustomer name: %s\n", customer.getDisplayName());
        }
      }
    } while (pageToken != null);

    if (noData) {
      System.out.println("No customers were found associated with the authorized user.");
    }
  }
}

      

后续步骤

  • 参阅广告数据中心内的示例查询,查看您可以通过 Ads Data Hub REST API 创建和运行的查询示例。
  • 在示例的基础上进行扩展,以熟悉该 API,并针对您的用例对其进行自定义。然后尝试:
  • 如果您有关于该 API 的问题或反馈意见,可与广告数据中心支持团队联系。