アプリケーションの設定
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
クライアント ライブラリを使用している場合は、アプリケーションで Doubleclicksearch
サービス オブジェクトをインスタンス化する必要があります。検索広告 360 API とのすべてのやり取りは、このサービス オブジェクトを介して行われます。クライアント ライブラリを使用していない場合は、このセクションをスキップできますが、HTTP リクエストを送信してレスポンスを解析できるコードを記述する必要があります。
各 Doubleclicksearch
インスタンスには、認証情報と OAuth 2.0 アクセス トークンを含むオブジェクトへの参照が必要です。Doubleclicksearch
は、各リクエストで認証情報とトークンを検索広告 360 API に渡します。次のコードは、インストール済みアプリケーションの OAuth 2.0 を使用して Doubleclicksearch
サービス オブジェクトをインスタンス化する方法を示しています。
検索広告 360 API の OAuth 2.0 認証情報をまだ取得していない場合は、承認を設定するをご覧ください。
Java
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.doubleclicksearch.Doubleclicksearch;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Arrays;
private static final String[] SCOPES =
new String[] {
"https://www.googleapis.com/auth/doubleclicksearch"
};
/** File for storing user credentials. */
private static final java.io.File DATA_STORE_FILE =
new File(System.getProperty("user.home"), ".credentials/doubleclicksearch.json");
/**
* Global instance of the {DataStoreFactory}. The best practice is to make it a single
* globally shared instance across your application.
*/
private static FileDataStoreFactory dataStoreFactory;
/**
* Sets up a new Doubleclicksearch service. The builder for the service
* requires a Credential object, which provides the credentials needed to
* interact with Search Ads 360.
*/
private static Doubleclicksearch getService() throws Exception {
JsonFactory jsonFactory = new JacksonFactory();
NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
Credential credential = readCredentialFromCommandLine(jsonFactory, transport);
return new Doubleclicksearch.Builder(transport, jsonFactory, credential)
.setApplicationName("Sample")
.build();
}
/**
* Generates a credential by reading client id, client secret and refresh
* token from the command line. You could update this method to read the
* data from a database or other secure location.
*/
private static Credential readCredentialFromCommandLine(
JsonFactory jsonFactory,
NetHttpTransport transport) {
String clientId = System.console().readLine("Client id: ");
String clientSecret = System.console().readLine("Client secret: ");
String refreshToken = System.console().readLine("Refresh token: ");
return new GoogleCredential.Builder()
.setJsonFactory(jsonFactory)
.setTransport(transport)
.setClientSecrets(clientId, clientSecret)
.build()
.setRefreshToken(refreshToken);
}
/**
* This method is an alternative to {@link #readCredentialFromCommandLine}. It reads
* client secrets from a {@code client_secrets.json} file, interactively creates
* the necessary authorization tokens on first run, and stores the tokens in the
* {@code FileDataStore}. Subsequent runs will no longer require interactivity
* as long as the {@code .credentials/doubleclicksearch.json} file is not removed.
* You can download the {@code .credentials/doubleclicksearch.json} file from the
* Google API Console.
* Note that setting the {@link GoogleAuthorizationCodeFlow} access type
* to {@code offline} is what causes {@code GoogleAuthorizationCodeFlow} to obtain
* and store refresh tokens.
*/
private static Credential generateCredentialInteractively(
JsonFactory jsonFactory,
NetHttpTransport transport) throws Exception {
dataStoreFactory = new FileDataStoreFactory(DATA_STORE_FILE);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
jsonFactory, new InputStreamReader(
Doubleclicksearch.class.getResourceAsStream("/client_secrets.json")));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
transport, jsonFactory, clientSecrets, Arrays.asList(SCOPES))
.setDataStoreFactory(dataStoreFactory)
.setAccessType("offline")
.build();
return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
}
.NET
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using api = Google.Apis.Doubleclicksearch.v2;
/// <summary>
/// Creates a Doubleclicksearch API service with static credentials.
/// </summary>
/// <param name="clientId">API project client ID.<param>
/// <param name="clientSecret">API project client secret.<param>
/// <param name="refreshToken">Refresh token generated for installed applications.<param>
private static api.DoubleclicksearchService CreateService(
String clientId,
String clientSecret,
String refreshToken)
{
var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse
{
RefreshToken = refreshToken,
};
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret,
},
}), "user", token);
return new api.DoubleclicksearchService(
new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credentials,
ApplicationName = "Sample DS API client",
});
}
Python
import argparse
import httplib2
from apiclient.discovery import build
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client.client import OAuth2Credentials, HttpAccessTokenRefreshError
def create_credentials(client_id, client_secret, refresh_token):
"""Create Google OAuth2 credentials.
Args:
client_id: Client id of a Google Cloud console project.
client_secret: Client secret of a Google Cloud console project.
refresh_token: A refresh token authorizing the Google Cloud console project
to access the DS data of some Google user.
Returns:
OAuth2Credentials
"""
return OAuth2Credentials(access_token=None,
client_id=client_id,
client_secret=client_secret,
refresh_token=refresh_token,
token_expiry=None,
token_uri=GOOGLE_TOKEN_URI,
user_agent=None)
def get_service(credentials):
"""Set up a new Doubleclicksearch service.
Args:
credentials: An OAuth2Credentials generated with create_credentials, or
flows in the oatuh2client.client package.
Returns:
An authorized Doubleclicksearch serivce.
"""
# Use the authorize() function of OAuth2Credentials to apply necessary credential
# headers to all requests.
http = credentials.authorize(http = httplib2.Http())
# Construct the service object for the interacting with the Search Ads 360 API.
service = build('doubleclicksearch', 'v2', http=http)
return service
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Sample DS API code.')
parser.add_argument('--client_id', dest='c_id', action='store',
help=('Specifies the DS API client_id. Looks like: '
'1234567890.apps.googleusercontent.com'),
required=True)
parser.add_argument('--client_secret', dest='secret', action='store',
help=('Specifies the DS API client_secret. Looks like: '
'1ab2CDEfghigKlM3OPzyx2Q'),
required=True)
parser.add_argument('--refresh_token', dest='token', action='store',
help=('Specifies the DS API refresh_token. Looks like: '
'4/abC1ddW3WJURhF7DUj-6FHq8kkE'),
required=True)
args = parser.parse_args()
creds = create_credentials(args.c_id, args.secret, args.token)
try:
service = get_service(creds)
print 'Successfully loaded credentials.'
except HttpAccessTokenRefreshError:
print ('Error: Unable to get credentials. Please ensure that the '
'credentials are correct. '
'https://developers.google.com/search-ads/v2/authorizing'
)
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2024-11-23 UTC。
[null,null,["最終更新日 2024-11-23 UTC。"],[[["\u003cp\u003eThe Search Ads 360 API interacts through the \u003ccode\u003eDoubleclicksearch\u003c/code\u003e service object, requiring instantiation for usage.\u003c/p\u003e\n"],["\u003cp\u003eEach \u003ccode\u003eDoubleclicksearch\u003c/code\u003e instance needs credentials and an OAuth 2.0 access token to communicate with the API.\u003c/p\u003e\n"],["\u003cp\u003eCode examples in Java, .NET, and Python demonstrate how to create and set up the \u003ccode\u003eDoubleclicksearch\u003c/code\u003e service object with the required authentication information.\u003c/p\u003e\n"],["\u003cp\u003eObtain OAuth 2.0 credentials using the provided setup guide before proceeding with API integration.\u003c/p\u003e\n"]]],["Applications using client libraries interact with the Search Ads 360 API via a `Doubleclicksearch` service object, which requires OAuth 2.0 credentials. These credentials, including client ID, client secret, and refresh token, are passed to the API with each request. Code examples in Java, .NET, and Python demonstrate creating this service object. The Java example shows reading credentials from the command line or a JSON file, while .NET and Python illustrate setting credentials with a token response.\n"],null,["# Set Up Your Application\n\nIf you are using a client library, your application will need to instantiate a\n`Doubleclicksearch` service object. All interaction with the Search Ads 360 API\noccurs through this service object. If you aren't using a client library\nyou can skip this section, but you'll need to write some code that can send HTTP requests\nand parse the responses.\n\nEach `Doubleclicksearch` instance needs a\nreference to an object that contains your credentials and OAuth 2.0 access token.\n`Doubleclicksearch` will pass the credentials and token to the Search Ads 360 API\nin each request. The following code demonstrates how to instantiate a `Doubleclicksearch`\nservice object using OAuth 2.0 for installed applications.\n\nIf you haven't already obtained your OAuth 2.0 credentials for the Search Ads 360 API,\nsee [Set Up Authorization](/search-ads/v2/authorizing). \n\n### Java\n\n```python\nimport com.google.api.client.auth.oauth2.Credential;\nimport com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;\nimport com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;\nimport com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;\nimport com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;\nimport com.google.api.client.googleapis.auth.oauth2.GoogleCredential;\nimport com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;\nimport com.google.api.client.http.javanet.NetHttpTransport;\nimport com.google.api.client.json.JsonFactory;\nimport com.google.api.client.json.jackson2.JacksonFactory;\nimport com.google.api.client.util.store.DataStoreFactory;\nimport com.google.api.client.util.store.FileDataStoreFactory;\nimport com.google.api.services.doubleclicksearch.Doubleclicksearch;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintStream;\nimport java.util.Arrays;\n\nprivate static final String[] SCOPES =\n new String[] {\n \"https://www.googleapis.com/auth/doubleclicksearch\"\n };\n\n/** File for storing user credentials. */\nprivate static final java.io.File DATA_STORE_FILE =\n new File(System.getProperty(\"user.home\"), \".credentials/doubleclicksearch.json\");\n\n/**\n * Global instance of the {DataStoreFactory}. The best practice is to make it a single\n * globally shared instance across your application.\n */\nprivate static FileDataStoreFactory dataStoreFactory;\n\n/**\n * Sets up a new Doubleclicksearch service. The builder for the service\n * requires a Credential object, which provides the credentials needed to\n * interact with Search Ads 360.\n */\nprivate static Doubleclicksearch getService() throws Exception {\n JsonFactory jsonFactory = new JacksonFactory();\n NetHttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();\n\n Credential credential = readCredentialFromCommandLine(jsonFactory, transport);\n\n return new Doubleclicksearch.Builder(transport, jsonFactory, credential)\n .setApplicationName(\"Sample\")\n .build();\n}\n\n/**\n * Generates a credential by reading client id, client secret and refresh\n * token from the command line. You could update this method to read the\n * data from a database or other secure location.\n */\nprivate static Credential readCredentialFromCommandLine(\n JsonFactory jsonFactory,\n NetHttpTransport transport) {\n String clientId = System.console().readLine(\"Client id: \");\n String clientSecret = System.console().readLine(\"Client secret: \");\n String refreshToken = System.console().readLine(\"Refresh token: \");\n return new GoogleCredential.Builder()\n .setJsonFactory(jsonFactory)\n .setTransport(transport)\n .setClientSecrets(clientId, clientSecret)\n .build()\n .setRefreshToken(refreshToken);\n}\n\n/**\n * This method is an alternative to {@link #readCredentialFromCommandLine}. It reads\n * client secrets from a {@code client_secrets.json} file, interactively creates\n * the necessary authorization tokens on first run, and stores the tokens in the\n * {@code FileDataStore}. Subsequent runs will no longer require interactivity\n * as long as the {@code .credentials/doubleclicksearch.json} file is not removed.\n * You can download the {@code .credentials/doubleclicksearch.json} file from the\n * Google API Console.\n * Note that setting the {@link GoogleAuthorizationCodeFlow} access type\n * to {@code offline} is what causes {@code GoogleAuthorizationCodeFlow} to obtain\n * and store refresh tokens.\n */\nprivate static Credential generateCredentialInteractively(\n JsonFactory jsonFactory,\n NetHttpTransport transport) throws Exception {\n dataStoreFactory = new FileDataStoreFactory(DATA_STORE_FILE);\n GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(\n jsonFactory, new InputStreamReader(\n Doubleclicksearch.class.getResourceAsStream(\"/client_secrets.json\")));\n GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(\n transport, jsonFactory, clientSecrets, Arrays.asList(SCOPES))\n .setDataStoreFactory(dataStoreFactory)\n .setAccessType(\"offline\")\n .build();\n return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize(\"user\");\n}\n```\n\n### .NET\n\n```gdscript\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading;\n\nusing Google.Apis.Auth.OAuth2;\nusing Google.Apis.Auth.OAuth2.Flows;\nusing api = Google.Apis.Doubleclicksearch.v2;\n\n/// \u003csummary\u003e\n/// Creates a Doubleclicksearch API service with static credentials.\n/// \u003c/summary\u003e\n/// \u003cparam name=\"clientId\"\u003eAPI project client ID.\u003cparam\u003e\n/// \u003cparam name=\"clientSecret\"\u003eAPI project client secret.\u003cparam\u003e\n/// \u003cparam name=\"refreshToken\"\u003eRefresh token generated for installed applications.\u003cparam\u003e\nprivate static api.DoubleclicksearchService CreateService(\n String clientId,\n String clientSecret,\n String refreshToken)\n{\n var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse\n {\n RefreshToken = refreshToken,\n };\n var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(\n new GoogleAuthorizationCodeFlow.Initializer\n {\n ClientSecrets = new ClientSecrets\n {\n ClientId = clientId,\n ClientSecret = clientSecret,\n },\n }), \"user\", token);\n\n return new api.DoubleclicksearchService(\n new Google.Apis.Services.BaseClientService.Initializer\n {\n HttpClientInitializer = credentials,\n ApplicationName = \"Sample DS API client\",\n });\n}\n```\n\n### Python\n\n```python\nimport argparse\nimport httplib2\nfrom apiclient.discovery import build\nfrom oauth2client import GOOGLE_TOKEN_URI\nfrom oauth2client.client import OAuth2Credentials, HttpAccessTokenRefreshError\n\n\ndef create_credentials(client_id, client_secret, refresh_token):\n \"\"\"Create Google OAuth2 credentials.\n\n Args:\n client_id: Client id of a Google Cloud console project.\n client_secret: Client secret of a Google Cloud console project.\n refresh_token: A refresh token authorizing the Google Cloud console project\n to access the DS data of some Google user.\n\n Returns:\n OAuth2Credentials\n \"\"\"\n return OAuth2Credentials(access_token=None,\n client_id=client_id,\n client_secret=client_secret,\n refresh_token=refresh_token,\n token_expiry=None,\n token_uri=GOOGLE_TOKEN_URI,\n user_agent=None)\n\n\ndef get_service(credentials):\n \"\"\"Set up a new Doubleclicksearch service.\n\n Args:\n credentials: An OAuth2Credentials generated with create_credentials, or\n flows in the oatuh2client.client package.\n Returns:\n An authorized Doubleclicksearch serivce.\n \"\"\"\n # Use the authorize() function of OAuth2Credentials to apply necessary credential\n # headers to all requests.\n http = credentials.authorize(http = httplib2.Http())\n\n # Construct the service object for the interacting with the Search Ads 360 API.\n service = build('doubleclicksearch', 'v2', http=http)\n return service\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Sample DS API code.')\n parser.add_argument('--client_id', dest='c_id', action='store',\n help=('Specifies the DS API client_id. Looks like: '\n '1234567890.apps.googleusercontent.com'),\n required=True)\n parser.add_argument('--client_secret', dest='secret', action='store',\n help=('Specifies the DS API client_secret. Looks like: '\n '1ab2CDEfghigKlM3OPzyx2Q'),\n required=True)\n parser.add_argument('--refresh_token', dest='token', action='store',\n help=('Specifies the DS API refresh_token. Looks like: '\n '4/abC1ddW3WJURhF7DUj-6FHq8kkE'),\n required=True)\n args = parser.parse_args()\n\n creds = create_credentials(args.c_id, args.secret, args.token)\n try:\n service = get_service(creds)\n print 'Successfully loaded credentials.'\n except HttpAccessTokenRefreshError:\n print ('Error: Unable to get credentials. Please ensure that the '\n 'credentials are correct. '\n 'https://developers.google.com/search-ads/v2/authorizing'\n )\n```"]]