Google ads api —— Authentication & REST methods

https://developers.google.com/google-ads/api/docs/oauth/overview

OAuth2 in the Google Ads API

All Google Ads API calls must be authorized through OAuth2. OAuth2 enables your Google Ads API client app to access a user's Google Ads account without having to handle or store the user's login info.

 
The following steps must be completed to authorize requests to the Google Ads API.
  1. Configure a Cloud project for the Google Ads API

  2. Configure a client library for OAuth in the Google Ads API

Supporting materials are also available for related topics.

https://developers.google.com/google-ads/api/docs/oauth/internals

OAuth2 Internals for Google Ads API

Our client libraries automatically take care of the details covered below, so continue reading only if you're interested in what's happening behind the scenes, or if you're not using one of our client libraries.

This section is intended for advanced users who are already familiar with the OAuth 2.0 specification and know how to use OAuth2 with Google APIs.

Scope

A single access token can grant varying degrees of access to multiple APIs. A variable parameter called scope controls the set of resources and operations that an access token permits. During the access token request, your app sends one or more values in the scope parameter.

The present scope for the Google Ads API is: https://www.googleapis.com/auth/adwords

Offline access

It's common for a Google Ads API client app to request offline access. For example, your app may want to run batch jobs when your user is not physically online browsing your website.

To request offline access for a web app type, make sure you set the access_type parameter to offline. You can find additional information in Google's OAuth2 guide.

For the desktop app type, offline access is enabled by default—you don't have to explicitly request it.

Request headers

gRPC headers

When using the gRPC API, include the access token in each request. You can bind a Credential to a Channel for use on all requests on that channel. You can also send a customized credential for each call. The gRPC Authorization guide contains more details on handling authorization.

REST headers

When using the REST API, pass the access token through the HTTP header Authorization. An example HTTP request is shown below:

 
GET /v9/customers/123456789 HTTP/2
Host: googleads.googleapis.com
User-Agent: INSERT_USER_AGENT
Accept: */*
Authorization: Bearer INSERT_ACCESS_TOKEN
developer-token: INSERT_DEVELOPER_TOKEN

Access and refresh token

In most cases, you need to store the refresh token securely for future use. To learn more about how to request access and refresh tokens, read the corresponding guide for your application type:

Refresh token expiration

For more details about the refresh token expiration, refer to the Google Identity Platform OAuth documentation.

Access token expiration

An access token has an expiration time (based on the expires_in value) after which the token is no longer valid. You can use the refresh token to refresh an expired access token. By default, our client libraries automatically refresh expired access tokens.

REST Interface

Key Point: We strongly recommend using our official client libraries wherever you can. All Google provided client libraries are implemented using gRPC, except for the Perl library, which uses the REST interface. Unless you are specifically looking for details about REST, consult the gRPC documentation for reference documentation that covers our official client libraries.

The Google Ads API can be called either using gRPC or REST. Both interfaces expose a resource-oriented design shared with other Google Cloud APIs.

We recommend using Google's official client libraries wherever possible. They provide idiomatic, type-safe code in each supported language and handle many low-level details of communication with the API (like timeout settings, result set pagination, and authentication). Our client libraries also include an extensive set of code examples and utilities that assist with common tasks, such as constructing resource names and handling field masks.

This guide presents details specific to REST and explains what you need to know to call the REST interface directly, without the use of a Google-supported client library. This guide may be useful if you are writing your own custom code to use REST directly or using a third-party HTTP client library.

Note: Check out this talk about working with REST using the Google Ads API from the Google Ads API Spring 2019 Workshop.
 
 
https://developers.google.com/google-ads/api/rest/overview
 

Authorization and HTTP Headers

You need both OAuth 2.0 application credentials and a developer token when calling the Google Ads API. If you're making API calls as a Google Ads Manager Account, you also need to specify a login-customer-id header with each request. This page describes how to set these values and documents several additional API-specific HTTP headers that are sent and received when using the REST interface.

OAuth 2.0 credentials

The Google Ads API uses application credentials for identifying and authorizing API requests. Both OAuth 2.0 clients and service accounts can be configured. For more details about configuring client-side authorization, see OAuth2 in the Google Ads API.

If you are new to Google APIs, you can use oauth2l or the OAuth 2.0 Playground to experiment with application credentials and the Google Ads API before writing the code for your app.

Using desktop or web app flows

Follow the steps to configure a Google API Console project for the Google Ads API. Record the client ID and client secret, then come back to this page.

Once you've created an OAuth client, follow the desktop app flow instructions or the web app flow instructions to generate a refresh token and an access token.

Using service accounts

Follow the common instructions in the Service Accounts guide to set up service account access for the Google Ads API.

Once you've set up a service account to access your Google Ads account, follow the Using OAuth 2.0 for Server to Server Applications guide, making sure to select the HTTP/REST tab. The scope to use for Google Ads API access is https://www.googleapis.com/auth/adwords.

Generating new access tokens

Once you have a client ID, client secret, and refresh token, you can generate a new access token for use in API calls with the curl command line tool:

Note: The version v3 in the OAuth endpoint URL is unrelated to the Google Ads API version and should not change when migrating to newer versions of Google Ads API.
 
curl \
  --data "grant_type=refresh_token" \
  --data "client_id=CLIENT_ID" \
  --data "client_secret=CLIENT_SECRET" \
  --data "refresh_token=REFRESH_TOKEN" \
  https://www.googleapis.com/oauth2/v3/token

You then use the access token returned by the curl request in the Authorization HTTP header of every API call to the Google Ads API:

 
GET /v9/customers:listAccessibleCustomers HTTP/1.1
Host: googleads.googleapis.com
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN

Request headers

Developer token

The Google Ads API also requires a developer token in order to make calls to the API. You can apply for a token for your Manager Account directly from the Google Ads UI. For more details about getting set up with a developer token, see Obtain Your Developer Token.

You need to include your developer token value in the developer-token HTTP header of every API call to the Google Ads API:

 
GET /v9/customers:listAccessibleCustomers HTTP/1.1
Host: googleads.googleapis.com
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN

Login customer ID

For Google Ads API calls made by a manager to a client account (that is, when logging in as a manager to make API calls to one of its client accounts), you also need to supply the login-customer-id HTTP header. This value represents the Google Ads customer ID of the manager making the API call.

Including this header is equivalent to choosing an account in the Google Ads UI after signing in or clicking on your profile image at the top-right corner of the page. When specifying the customer ID, be sure to remove any hyphens (—), for example: 1234567890, not 123-456-7890.

 
GET /v9/customers:listAccessibleCustomers HTTP/1.1
Host: googleads.googleapis.com
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN
login-customer-id: MANAGER_CUSTOMER_ID
Key Point: If you're not authorizing as a Manager Account (in other words, if your OAuth 2.0 credentials are for a user of the target Google Ads client account directly), you do not need to supply a login-customer-id header.

Linked customer ID

This header is only used by third-party app analytics providers when uploading conversions to a linked Google Ads account. See the API Call Structure guide for more details.

 
...
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN
login-customer-id: MANAGER_CUSTOMER_ID
linked-customer-id: LINKED_CUSTOMER_ID

Response headers

The following headers are returned in HTTP responses from the API.

Request ID

The request-id is a string that uniquely identifies the API request. When debugging or troubleshooting problems with specific API calls, the request-id is an important identifier to have handy when contacting Google developer support.

 
request-id: 2a5Cj89VV7CNhya1DZjjrC

https://developers.google.com/google-ads/api/rest/common/search

Search & SearchStream

Note: See the Search section of the accompanying examples for more complete examples.

The Google Ads API has a unified attribute retrieval and metrics reporting mechanism that lets you create queries using the Google Ads Query Language. This enables complex queries that can return large quantities of data about individual Google Ads accounts.

You can create queries using either of the Search or SearchStream methods. Both methods support the same queries and return equivalent results. The Search method returns data in customizable page sizes, enabling you to iterate over a result set using pagination. This could be advantageous in low bandwidth or unreliable network conditions, for example, to segment a large result set into smaller responses that can be re-fetched if a connection is lost. The SearchStream method, on the other hand, streams the entire result set back in a single response, which can be more efficient for bulk data retrieval.

Both Search and SearchStream use the same base URL:

 
    https://googleads.googleapis.com/v9/customers/CUSTOMER_ID/googleAds

The page-based search method takes an optional pageSize parameter which limits how many results are returned in a single API response.

Note: The pageSize parameter is optional and will default to 10,000 if not explicitly set.
 
POST /v9/customers/CUSTOMER_ID/googleAds:search HTTP/1.1
Host: googleads.googleapis.com
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN

{
"pageSize": 10000,
"query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'"
}

If there are more rows in the results than pageSize, a nextPageToken is returned in the response:

 
{
  "results": [
    // ...
    // ...
    // ...
  ],
  "nextPageToken": "CPii5aS87vfFTBAKGJvk36qpLiIWUW5SZk8xa1JPaXJVdXdIR05JUUpxZyoCVjMwADjUBkD___________8B",
  "fieldMask": "adGroupCriterion.keyword.text,adGroupCriterion.status"
}

Repeating the same query with a pageToken added with the value above fetches the next page of results:

 
POST /v9/customers/CUSTOMER_ID/googleAds:search HTTP/1.1
Host: googleads.googleapis.com
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN

{
"pageSize": 10000,
"query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'",
"pageToken": "CPii5aS87vfFTBAKGJvk36qpLiIWUW5SZk8xa1JPaXJVdXdIR05JUUpxZyoCVjMwADjUBkD___________8B"
}

To use the SearchStream method, which returns all results in a single streamed response, simply change the service method in the URL to searchStream (pageSize and pageToken are not required by SearchStream):

 
POST /v9/customers/CUSTOMER_ID/googleAds:searchStream HTTP/1.1
Host: googleads.googleapis.com
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN

{
    "query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'"
}
Note: The results of a SearchStream API call are wrapped in a JSON array, whereas most other API calls return a single JSON object as the response message. See the JSON mappings section for more info.
https://developers.google.com/google-ads/api/rest/examples#curl

Examples

This guide contains examples of calling the REST endpoints directly, without the use of a client library.

Prerequisites

All the samples below are meant to be easily copy-and-pasteable into a bash shell using curl command.

You will also need a developer token (test account access is fine) and a Google Ads manager account containing at least one client account.

Important: In these examples, we assume that you are accessing a client account (CUSTOMER_ID) by a user that has administrative access to a manager account (MANAGER_CUSTOMER_ID) that directly manages the client account. If you are instead accessing an individual client account directly, omit the login-customer-id header or set it to the same value as CUSTOMER_ID. Note that some examples, like Creating accounts, require a manager account.

Environment variables

Enter account credentials and IDs below, and then copy-and-paste into your terminal to configure the environment variables used in the subsequent examples.

Note: The Authorization guide provides instructions for generating an OAuth 2.0 access token.
 
API_VERSION="9"
DEVELOPER_TOKEN="DEVELOPER_TOKEN"
OAUTH2_ACCESS_TOKEN="OAUTH_ACCESS_TOKEN"
MANAGER_CUSTOMER_ID="MANAGER_CUSTOMER_ID"
CUSTOMER_ID="CUSTOMER_ID"

Additional optional object IDs

Some of the following examples work on pre-existing budgets or campaigns. If you have IDs of existing objects to use with these examples, enter them below.

 
BUDGET_ID=BUDGET_ID
CAMPAIGN_ID=CAMPAIGN_ID

Otherwise, the two Mutates - Creates examples will create a new budget and campaign.

Note: The Query Cookbook guide contains many reporting samples that correspond to some of the default Google Ads screens and work with the same environment variables used in this guide. Our interactive query builder tool is also a great resource for building custom queries interactively.

Paginated

The search method uses pagination, with an adjustable pageSize parameter specified alongside the query.

curl -f --request POST "https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search" \
--header "Content-Type: application/json" \
--header "developer-token: ${DEVELOPER_TOKEN}" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--data '{
"pageSize": 10,
"query": "
  SELECT campaign.name,
    campaign_budget.amount_micros,
    campaign.status,
    campaign.optimization_score,
    campaign.advertising_channel_type,
    metrics.clicks,
    metrics.impressions,
    metrics.ctr,
    metrics.average_cpc,
    metrics.cost_micros,
    campaign.bidding_strategy_type
  FROM campaign
  WHERE segments.date DURING LAST_7_DAYS
    AND campaign.status != 'REMOVED'
"
}'

Streaming

The searchStream method streams all results in a single response, and thus the pageSize field is not supported.

curl -f --request POST "https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:searchStream" \
--header "Content-Type: application/json" \
--header "developer-token: ${DEVELOPER_TOKEN}" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--data '{
"query": "
  SELECT campaign.name,
    campaign_budget.amount_micros,
    campaign.status,
    campaign.optimization_score,
    campaign.advertising_channel_type,
    metrics.clicks,
    metrics.impressions,
    metrics.ctr,
    metrics.average_cpc,
    metrics.cost_micros,
    campaign.bidding_strategy_type
  FROM campaign
  WHERE segments.date DURING LAST_7_DAYS
    AND campaign.status != 'REMOVED'
"
}'

Mutates

Multiple mutate operations (create, update, or remove) can be sent in a single JSON request body by populating the operations array.

https://developers.google.com/google-ads/api/rest/design/overview

Resource Names

Name hierarchy

Resource names used in the Google Ads API are hierarchical, mirroring the organization of entities within Google Ads. Almost all resources are sub-resources of the Customer resource, which reflects the fact that almost every API call has to target a specific Google Ads account. For example, campaigns, ad groups, ads, and keywords are all sub-resources of a root customer resource.

ResourceResource Name
Customer customers/1234567890
Campaign customers/1234567890/campaigns/8765432109
AdGroup customers/1234567890/adGroups/54321098765
AdGroupAd customers/1234567890/adGroupAds/54321098765~2109876543210

Key Point: Google Ads API uses relative resource names (and not full resource names like some other Google APIs).

Resource IDs

Google Ads entities (customers, campaigns, etc.) are referred to by their resource names throughout the API. However, it's important to note that the resource names themselves may have unique numerical resource IDs that identify each object in the hierarchy. In these cases, it may be useful to parse the resource name to extract these resource IDs and assemble a new one.

For example, examine the AdGroupAd resource name from the previous table:

 
customers/1234567890/adGroupAds/54321098765~2109876543210

This can be broken down into its individual resource IDs (separated by collection IDs) as follows:

Resource name components
Resource IDs
customer ID:
"1234567890"
ad group ID:
"54321098765"
ad group ad ID:
"2109876543210"
Collection IDs
"customers"
"adGroupAds"

Parsing the individual IDs lets you derive new resource names to reference the ad group ad's customer (customers/1234567890) or its ad group (customers/1234567890/adGroupAds/54321098765).

Key Point: Resource names in JSON request and response bodies are referred to by the resourceName field, not the name field like in some other Google Cloud APIs. Many Google Ads entities have name attributes themselves (campaign.Name, adGroup.Name, etc.), so resourceName is used to avoid collision with existing object names.

Identifiers of shared objects

Most objects in the API are associated with a single specific Google Ads customer. However, there are some object types that can be shared between multiple accounts. In practice, these are things like negative keyword lists or cross-account conversion actions that are usually created by managers and then shared with many client accounts.

The resource names of objects like these will differ, depending on which account you're sending an API call to.

Example: Cross-account conversion actions

Assume we have manager account 987-654-3210 that shares a cross-account conversion action with one of its client customer accounts 123-456-7890:

Diagram showing relationship of resource names to account hierarchies.

Making an API call to the manager account to, for example, update the conversion action's lookback window would reference the shared object using resource name: customers/9876543210/conversionActions/257733534.

Making an API call to the client account to opt-in to using the shared conversion action would reference it using resource name: customers/1234567890/conversionActions/257733534.

This is the same underlying conversion action, but its resource name is relative to the account used to access it.

JSON Mappings

When using the Google Ads API's REST interface, you're working with JSON representations of the same resources and types defined in the Google Ads API's .proto descriptor files. The JSON encoding scheme follows the canonical encoding scheme described in the JSON Mapping section of the protocol buffers Language Guide.

In general, all top-level messages to and from services are single JSON objects. Most mutate requests contain an operations array that itself contains many create, update, or delete operations. Similarly, search responses are JSON objects containing a results array with your query's result set.

Identifiers are transformed from snake_case (in protocol buffers) to lowerCamelCase in JSON. One notable caveat to this rule is when using search or searchStream to send Google Ads Query Language queries. The query language itself uses snake case, regardless of which interface you're using. However, the results of a query in REST are returned as normal JSON objects and have their identifiers in lowerCamelCase.

For example, a query to fetch a list of active keywords in an account uses snake case inside the query itself (ad_group_criterion, not adGroupCriterion):

 
POST /v9/customers/CUSTOMER_ID/googleAds:searchStream HTTP/1.1
Host: googleads.googleapis.com
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN
developer-token: DEVELOPER_TOKEN

{
  "query": "SELECT ad_group_criterion.keyword.text
            FROM ad_group_criterion
            WHERE ad_group_criterion.type = 'KEYWORD'
            AND ad_group_criterion.status = 'ENABLED'"

}

However, the response is a JSON representation of the objects (wrapped in a JSON array since this request uses searchStream) and uses the camelCase identifier adGroupCriterion instead:

 
 
[
  {
    "results": [
      {
        "adGroupCriterion": {
          "resourceName": "customers/1842689525/adGroupCriteria/55771861891~10003060",
          "keyword": {
            "text": "pay per click"
          }
        }
      },
      ...
    ]
  }
]

REST Interface Design

This page assumes a familiarity with the Resource Oriented Design and Resource Names developer guides and complements them with specific implementation details of the Google Ads API.

Key Point: The examples throughout this guide use HTTP protocol to demonstrate how to call the API. See the Examples page for how you can make these same API calls using the curl command line utility.

Resource-oriented design

Generally, the Google Ads API follows a resource-oriented design, modeled as collections of individually-addressable resources (the nouns of the API). Resources are referenced with their resource names and manipulated using a small set of methods (also known as verbs or operations).

These resource names and methods, combined with a specific API version prefix, comprise the URLs of the REST interface. For example, the URL below can be broken down into these individual components according to the following table:

 
https://googleads.googleapis.com/v9/customers/1234567890:mutate
API Version PrefixResource Name (relative)Method
https://googleads.googleapis.com/v9 customers/1234567890 mutate

All REST URLs for a particular version of the API (e.g., v9) share a common API version prefix. The resource name and method together identifies which API service is being called.

The Google Ads API makes heavy use of custom methods, as opposed to most traditional REST APIs that use standard REST methods such as list, get, create, update, and delete. Examples of custom methods in the Google Ads API include search, searchStream, and mutate.

The following pages go into more details about the Google Ads API's resource names, service methods, and JSON naming conventions to illustrate how they're used together to define REST interface endpoints.

原文地址:https://www.cnblogs.com/panpanwelcome/p/15793186.html