Get Started with the API

This document explains how to get started writing applications that use the DoubleClick Bid Manager API. The API enables developers to manage Queries, retrieve Report metadata, and download and upload LineItems.

Google DoubleClick Bid Manager API v1 is the latest available and recommended version.

1. Before you start

If you're unfamiliar with Bid Manager concepts, read the DoubleClick Bid Manager Help Center and experiment with the user interface.

2. Prepare for authentication

To get started using Google DoubleClick Bid Manager API, you need to first use the setup tool, which guides you through creating a project in the Google API Console, enabling the API, and creating credentials.

If you haven't done so already, create your OAuth 2.0 credentials by clicking Create credentials > OAuth client ID. After you've created the credentials, you can see your client ID on the Credentials page. Click the client ID for details, such as client secret, redirect URIs, JavaScript origins address, and email address.

For more information, see Authorize Requests.

3. Call the Bid Manager REST API

The tabs below provide quickstarts for coding in various languages. All of the code shown is included in the Bid Manager Examples repo

Java

Here is a basic example that shows how to use the Google DoubleClick Bid Manager API with Java.

  1. Create an Eclipse maven project

    Open the pom.xml and add these dependencies:

    <dependencies>
     <dependency>
        <groupId>com.google.apis</groupId>
        <artifactId>google-api-services-doubleclickbidmanager</artifactId>
        <version>v1-rev48-1.22.0</version>
      </dependency>
      <dependency>
        <groupId>com.google.http-client</groupId>
        <artifactId>google-http-client-jackson2</artifactId>
        <version>${project.http.version}</version>
      </dependency>
      <dependency>
        <groupId>com.google.oauth-client</groupId>
        <artifactId>google-oauth-client-jetty</artifactId>
        <version>${project.oauth.version}</version>
      </dependency>
    </dependencies>

  2. Load the client secrets file

    All calls to the API require authentication; load up the client secrets file you downloaded to create a GoogleClientSecrets object.

    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
        JSON_FACTORY, 
        new InputStreamReader(
            DoubleClickBidManagerFactory.class.getResourceAsStream("/client_secrets.json"),
            UTF_8));
  3. Get authorized credentials

    Create a Credential object using the GoogleClientSecrets.

    // Set up the authorization code flow.
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets,
            DoubleClickBidManagerScopes.all()).setDataStoreFactory(dataStoreFactory).build();
    
    // Authorize and persist credential information to the data store.
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  4. Construct a client for the Bid Manager service

    Use the Credential object to create an authenticated DoubleClickBidManager using the Builder pattern:

    DoubleClickBidManager bidmanager =
        new DoubleClickBidManager.Builder(HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(credential))
            .setApplicationName(APPLICATION_NAME + "_JavaSamples")
            .build();

  5. Perform operations

    After you've instantiated a client to connect to the API, you can begin performing operations. For example, you can make a listqueries request and display all available queries:

    // Call the API, getting a list of queries.
    ListQueriesResponse queryListResponse = service.queries().listqueries().execute();
    
    // Print them out.
    System.out.println("Id\t\tName");
    for (Query query : queryListResponse.getQueries()) {
      System.out.format("%s\t%s%n", query.getQueryId(), query.getMetadata().getTitle());
    }

    Or identify a specific query and download the latest report:

    // Retrieve the download URL for the latest report.
    GenericUrl reportUrl =
        new GenericUrl(query.getMetadata().getGoogleCloudStoragePathForLatestReport());
    
    // Download the report file.
    try (OutputStream output = new FileOutputStream(query.getQueryId() + ".csv")) {
      MediaHttpDownloader downloader = new MediaHttpDownloader(HTTP_TRANSPORT, null);
      downloader.download(reportUrl, output);
    }
    
    System.out.println("Download complete.");

For more detailed information about using the Google DoubleClick Bid Manager API with Java, refer to the README file in the Google DoubleClick Bid Manager API examples.

Python

Here is a basic example that shows how to use the Google DoubleClick Bid Manager API with Python.

  1. Download and install the Google API Python Client

    Example using pip:

    pip --upgrade google-api-python-client

  2. Get authorized credentials

    Use the Client ID and Secret from above to prompt for authorization.

    flow = client.OAuth2WebServerFlow(
        client_id=client_id, client_secret=client_secret,
        scope=[_SCOPE], user_agent=_USER_AGENT,
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    
    authorize_url = flow.step1_get_authorize_url()
    
    print ('Log into the Google Account you use to access your DBM account'
           'and go to the following URL: \n%s\n' % (authorize_url))
    print 'After approving the token enter the verification code (if specified).'
    code = raw_input('Code: ').strip()
    
    try:
      credentials = flow.step2_exchange(code)
    except client.FlowExchangeError, e:
      print 'Authentication has failed: %s' % e
      sys.exit(1)
    else:
      return credentials
  3. Construct a client for the Bid Manager service

    Create a client for the Bid Manager API passing in the latest version of the API.

    return build('doubleclickbidmanager', _VERSION,
                 http=credentials.authorize(httplib2.Http()))
  4. Perform operations

    After you've instantiated a client to connect to the API, you can begin performing operations. For example, you can make a listqueries request and display all available queries:

    # Call the API, getting a list of queries.
    response = doubleclick_bid_manager.queries().listqueries().execute()
    
    # Print queries out.
    print 'Id\t\tName'
    if 'queries' in response:
      for q in response['queries']:
        print '%s\t%s' % (q['queryId'], q['metadata']['title'])
    else:
      print 'No queries exist.

    Or identify a specific query and download the latest report:

    # Grab the report and write contents to a file.
    report_url = query['metadata']['googleCloudStoragePathForLatestReport']
    output_file = '%s/%s.csv' % (output_dir, query['queryId'])
    with open(output_file, 'wb') as output:
      with closing(urllib2.urlopen(report_url)) as url:
        output.write(url.read())
    print 'Download complete.

For more detailed information about using the Google DoubleClick Bid Manager API with Python, refer to the README file in the Google DoubleClick Bid Manager API examples.

PHP

Here is a basic example that shows how to use the Google DoubleClick Bid Manager API with PHP.

  1. Download and install the Google API PHP Client

    The preferred method is via Composer:

    composer require google/apiclient:^2.0

    Once installed, be sure to include the autoloader:

    require_once '/path/to/your-project/vendor/autoload.php';
  2. Create a Google_Client object.

    $client = new Google_Client();
  3. Set up your credentials

    All calls to the API require authentication; load up the client secrets file you downloaded and add a scope for your requests.

    $client->setApplicationName('DBM API PHP Samples');
    $client->addScope('https://www.googleapis.com/auth/doubleclickbidmanager');
    $client->setAccessType('offline');
  4. Construct a client for the Bid Manager service

    You can then create your DoubleClickBidManager client using the authorized Google_Client object:

    $service = new Google_Service_DoubleClickBidManager($client);

  5. Perform operations

    After you've instantiated a client to connect to the API, you can begin performing operations. For example, you can make a listqueries request and display all available queries:

    // Call the API, getting a list of queries.
    $result = $this->service->queries->listqueries();
    if (isset($result['queries']) && count($result['queries']) > 0) {
      print '<pre>';
      foreach ($result['queries'] as $query) {
        printf('<p>%s %s</p>', $query->queryId, $query->metadata->title);
      }
      print '</pre>';
    } else {
      print '<p>No reports found</p>';
    }

    Or identify a specific query and download the latest report:

    // Grab the report.
    file_put_contents($query->queryId . '.csv',
        fopen($query->metadata->googleCloudStoragePathForLatestReport,
            'r'));
    print '<p>Download complete.</p>';

For more detailed information about using the Google DoubleClick Bid Manager API with PHP, refer to the README file in the Google DoubleClick Bid Manager API examples.

4. Next steps

Now that you have a client library up and running, go ahead and look at the code examples to extend them for your needs.

Read the other topics listed in the Guides section for more inspiration.