Set Up Your Application

If you are using a client library, your application will need to instantiate a Doubleclicksearch service object. All interaction with the DoubleClick Search API occurs through this service object. If you aren't using a client library you can skip this section, but you'll need to write some code that can send HTTP requests and parse the responses.

Each Doubleclicksearch instance needs a reference to an object that contains your credentials and OAuth 2.0 access token. Doubleclicksearch will pass the credentials and token to the DoubleClick Search API in each request. The following code demonstrates how to instantiate a Doubleclicksearch service object using OAuth 2.0 for installed applications.

If you haven't already obtained your OAuth 2.0 credentials for the DoubleClick Search API, see Set Up Authorization.



import java.util.Arrays;

private static final String[] SCOPES =
    new String[] {

/** File for storing user credentials. */
private static final 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 DoubleClick Search service. The builder for the service
 * requires a Credential object, which provides the credentials needed to
 * interact with DoubleClick Search.
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)

 * 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()
      .setClientSecrets(clientId, clientSecret)

 * 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(
  GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
      transport, jsonFactory, clientSecrets, Arrays.asList(SCOPES))
  return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");


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 DoubleClick Search 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",


import argparse
import httplib2
from apiclient.discovery import build
from oauth2client import GOOGLE_TOKEN_URI
from oauth2client.client import OAuth2Credentials

def create_credentials(client_id, client_secret, refresh_token):
  """Create Google OAuth2 credentials.

    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.

  return OAuth2Credentials(access_token=None,

def get_service(credentials):
  """Set up a new DoubleClick Search service.

    credentials: An OAuth2Credentials generated with create_credentials, or
    flows in the oatuh2client.client package.
    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 DoubleClick Search 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: '
  parser.add_argument('--client_secret', dest='secret', action='store',
                      help=('Specifies the DS API client_secret. Looks like: '
  parser.add_argument('--refresh_token', dest='token', action='store',
                      help=('Specifies the DS API refresh_token. Looks like: '
  args = parser.parse_args()

  creds = create_credentials(args.c_id, args.secret, args.token)
  service = get_service(creds)

Enviar comentarios sobre…

DoubleClick Search API