Get Started with the AdMob API Beta

This guide is for developers who want to use the AdMob API Beta to programmatically get information about their AdMob account.

Prerequisites

Create a project

To get started using the AdMob API Beta, you need to first create or select a project in the Google API Console and enable the API using the setup tool, which guides you through the process and activates the AdMob API Beta automatically.

Generate credentials

All requests you make to the AdMob API Beta must be authorized. For a brief overview of authorization, read about how to authorize and identify your application to Google.

The following instructions guide you through the process of creating an OAuth 2.0 client ID to use with the installed application flow.

  1. Follow the steps to configure a Google API Console project.

  2. Open the Credentials page in the API Console.
  3. Click Create credentials > OAuth client ID.

  4. Select Other when prompted to select an application type and enter any additional required information.

    • If this is your first time creating a client ID, besides being able to select your application type, you can configure your consent screen by clicking the Configure consent screen button. You will not get a prompt to configure your consent screen again after you do it the first time, although this information can be updated at any time.
  5. Click Create.

When done, you'll be presented with an OAuth 2.0 client ID and client secret, which you can download in JSON format and save for later use.

Make a request

With OAuth 2.0 credentials created, you're ready to start using the AdMob API Beta.

The AdMob API Beta is built on HTTP and JSON, so any standard HTTP client can send requests to it and parse the responses. However, the Google API client libraries provide better language integration, improved security, and support for making authorized requests. The client libraries are available in a number of programming languages; by using them you can avoid the need to manually set up HTTP requests and parse the responses.

We now present a couple of ways to make your first request:

Java client library

Requests using a client library

  1. Load the client secrets file and generate authorization credentials.

    The first time you perform this step you'll be asked to accept an authorization prompt in your browser. Before accepting, make sure you're signed in with a Google Account that has access to the AdMob API Beta. Your application will be authorized to access data on behalf of whichever account is currently logged in.

    // Load the client secrets JSON file.
    
    String pathToClientSecretsFile = "INSERT_PATH_TO_CLIENT_SECRETS";
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(
            jsonFactory,
            Files.newBufferedReader(Paths.get(pathToClientSecretsFile), UTF_8)
        );
    
    // Set up the authorization code flow.
    //
    // Note: providing a DataStoreFactory allows auth credentials to be cached,
    // so they survive multiple runs of the program. This avoids prompting the
    // user for authorization every time the access token expires, by remembering
    // the refresh token.
    ImmutableSet<String> REPORT_SCOPE =
        ImmutableSet.of("https://www.googleapis.com/auth/admob.report");
    GoogleAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow.Builder(
            httpTransport, jsonFactory, clientSecrets, REPORT_SCOPE)
            .setDataStoreFactory(dataStoreFactory)
            .build();
    
    // Build installed application credential.
    Credential credential =
        getUserAccountCredential(pathToClientSecretsFile,
            new FileDataStoreFactory(DATA_STORE_DIR));
    
  2. Create an authorized AdMob client.

    // Create an AbMob client instance.
    AdMob client =
        new AdMob.Builder(credential.getTransport(),
                         credential.getJsonFactory(),
                         credential)
            .setApplicationName("admobapi-java-installed-app-sample")
            .build();
    
  3. Perform an operation.

    ListPublisherAccountsResponse accounts = client.accounts().list().execute();
    
    for (PublisherAccount account : accounts.getAccount()) {
      System.out.printf(
          "Publisher Name: %s, Publisher Id: %s, Currency Code: %s, "
              + "Reporting Time Zone: %s.\n",
          account.getName(),
          account.getPublisherId(),
          account.getCurrencyCode(),
          account.getReportingTimeZone());
    }
    

PHP client library

Requests using PHP client library

  1. Create an authorized AdMob client.

    The first time you perform this step you'll be asked to accept an authorization prompt in your browser. Before accepting, make sure you're signed in with a Google Account that has access to the AdMob API Beta. Your application will be authorized to access data on behalf of whichever account is currently logged in.

     // Create an AdMob Client.
     $client = new Google_Client();
     $client->addScope('https://www.googleapis.com/auth/admob.report');
     $client->setApplicationName('AdMob API PHP Quickstart');
     $client->setAccessType('offline');
    
     // Be sure to replace the contents of client_secrets.json with your developer
     // credentials.
     $client->setAuthConfig('client_secrets.json');
    
     // Create the URL for the authorization prompt.
     $authUrl = $client->createAuthUrl();
    
     // Once the authorization prompt has been accepted, exchange the
     // authorization code for an access and refresh token.
     $client->authenticate($_GET['code']);
     $client->getAccessToken();
    
  2. Create an AdMob service object.

    // Create an AbMob service object on which to run the requests.
    $service = new Google_Service_AdMob($client);
    
  3. Perform an operation.

    // Get AdMob account information by replacing account_name,
    // which follows the format "accounts/pub-XXXXXXXXXXXXXXXX".
    $service->accounts->get($account_name);
    

curl (command line)

Requests using curl

You can use curl to make HTTP requests. Follow these instructions to get account info and then generate a network report.

Get account info

You can request account info by calling get or list accounts methods.

Replace path_to_credentials_json with a path to a credentials.json file that you download when you register your cloud application. The first time, the command walks you through the OAuth 2.0 authorization flow. Subsequent runs refresh the token automatically.

Sample request:

curl -X GET https://admob.googleapis.com/v1/accounts \
       -H "$(oauth2l header --json path_to_credentials_json \
          https://www.googleapis.com/auth/admob.report)"

Sample response:

{
  "account": [
    {
      "publisherId": "pub-1234567890123456",
      "reportingTimeZone": "Europe/Paris",
      "currencyCode": "EUR"
    }
  ]
}

Generate a network report

You can generate a network report by calling the networkReport:generate method. Use the publisherId received in the Get account info step step as part of the request URI (for example, v1/accounts/pub-1234567890123456/networkReport:generate).

You must first get an access token to make the call:

  1. Visit oauth playground
  2. Under Step 1 Select & authorize APIs, enter the AdMob API Beta scope https://www.googleapis.com/auth/admob.report.
  3. Click Authorize APIs.
  4. Under Step 2 Exchange authorization code for tokens, select Exchange authorization code for tokens.
  5. Save the access and refresh token values. You will need the access token in the next step. The refresh token can be used to get a new access token when needed.

Then, use the following command to generate the network report:

curl -X POST \
          https://admob.googleapis.com/v1/accounts/pub-1234567890123456/networkReport:generate \
       -H "Authorization: Bearer access_token" \
       -H "Content-Type: application/json" \
       --data @- << EOF
{
  "report_spec": {
    "date_range": {
      "start_date": {"year": 2020, "month": 4, "day": 1},
      "end_date": {"year": 2020, "month": 4, "day": 2}
    },
    "dimensions": ["DATE"],
    "metrics": ["CLICKS", "AD_REQUESTS", "IMPRESSIONS", "ESTIMATED_EARNINGS"],
    "dimension_filters": [{"dimension": "COUNTRY", "matches_any": {"values": ["US"]}}],
    "sort_conditions": [{"metric":"CLICKS", order: "DESCENDING"}],
    "localization_settings": {"currency_code": "USD", "language_code": "en-US"}
  }
}
EOF

Sample response:

[{
  "header": {
    "dateRange": {
      "startDate": {"year": 2020, "month": 4, "day": 1},
      "endDate": {"year": 2020, "month": 4, "day": 2}
    }
  }
},
{
  "row": {
    "dimensionValues": {"DATE": {"value": "20200401"}},
    "metricValues": {
      "CLICKS": {"integerValue": "31"},
      "AD_REQUESTS": {"integerValue": "7409"},
      "IMPRESSIONS": {"integerValue": "3440"},
      "ESTIMATED_EARNINGS": {"microsValue": "6381903"}
    }
  }
},
{
  "row": {
    "dimensionValues": {"DATE": {"value": "20200402"}},
    "metricValues": {
      "CLICKS": {"integerValue": "30"},
      "AD_REQUESTS": {"integerValue": "8828"},
      "IMPRESSIONS": {"integerValue": "3724"},
      "ESTIMATED_EARNINGS": {"microsValue": "9010390"}
    }
  }
},
{
  "footer": {
    "matchingRowCount": "2"
  }
}]