Migrate from the AdSense API

The AdMob API allows you to programmatically get information on your AdMob account. If you use the AdSense API to access AdMob data, follow this guide to migrate to the AdMob API. The AdMob API replaces the need to use the AdSense API and provides enhanced capabilities:

  • Retrieve metrics that are consistent with the AdMob UI reports.
  • Gain access to mediation reporting programmatically, including Open Bidding.
  • Access to more metrics and dimensions.

If you were using one of the AdSense API client libraries, take a look at the AdMob API client libraries samples.

Account identifier

Account identifiers are still required for the AdMob API, but they follow a different format. See the instructions to find your publisher id, which follows the format of pub-xxxxxxxxxxxxxxxx.

AdSense API AdMob API
pub-xxxxxxxxxxxxxxxx accounts/pub-xxxxxxxxxxxxxxxx

Authentication

To start using the AdMob API, you will need to make some changes to your existing code. If you haven’t already, start with enabling the AdMob API.

If you are using the AdSense API, then you can use the same generated credentials to authenticate with the AdMob API, however, you will need to use the AdMob API scope.

The examples show how to replace the AdSense API scope with the AdMob API scope. The authorization sequence begins when your application redirects you to Google along with the list of requested permissions. Once you grant the requested permissions, your application retrieves the tokens needed to make API requests. Both the AdMob API and AdSense API use OAuth2.0 for authentication and authorization.

Scopes

AdSense API

Scope Meaning
https://www.googleapis.com/auth/adsense Read/write access to AdSense data.
https://www.googleapis.com/auth/adsense.readonly Read-only access to AdSense data.

AdMob API

Scope Meaning
https://www.googleapis.com/auth/admob.report Read access to AdMob data.

Methods

The AdMob API uses definitions consistent with the AdMob UI, which are explained below in the Network Report Dimensions. You may have noticed previously when accessing AdMob data from the AdSense API that the values may have not matched the AdMob UI. Now, with the AdMob API, the values are consistent with the AdMob UI.

Migrated methods

AdSense API AdMob API
adsense.accounts.reports.generate admob.accounts.networkReport:generate
adsense.accounts.list admob.accounts.list

Always returns a list with a single account.

adsense.accounts.get admob.account.get
N/A admob.accounts.mediationReport:generate

Report generation

This API is not intended for downloading large reports. Report size can be reduced by requesting smaller date ranges as well as reducing the number of dimensions per request.

Feature AdSense API AdMob API
Supports streaming Yes Yes
Supports pagination Yes No
Behavior when requesting over 100k rows Returns an error Returns 100k rows
Intended for large reports No No

Network report dimensions

The following AdSense API dimensions are relevant to AdMob data.

AdSense API AdMob API AdMob API Dimension Definition
DATE DATE A date in the YYYY-MM-DD format (for example, 2018-12-21). Requests can specify at most one time dimension.
MONTH MONTH A month in the YYYY-MM format (for example, 2018-12). Requests can specify at most one time dimension.
WEEK WEEK The date of the first day of a week, based on Localization Settings, in the YYYY-MM-DD format (for example, 2018-12-23). Requests can specify at most one time dimension.
AD_UNIT_CODE
AD_UNIT_NAME
AD_UNIT The unique ID of the ad unit (for example, ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX). If AD_UNIT dimension is specified, then APP is included automatically.
AD_UNIT_SIZE_CODE
AD_UNIT_SIZE_NAME
FORMAT Format of the ad unit (for example, banner, native), an ad delivery dimension.
APP_ID
APP_NAME
APP The unique ID of the mobile application (for example, ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX).
APP_PLATFORM PLATFORM Mobile OS platform of the app (for example, Android or iOS).
COUNTRY_CODE
COUNTRY_NAME
COUNTRY CLDR country code of the place where the ad views/clicks occur (for example, US or FR). This is ageography dimension.
N/A AD_TYPE Type of the ad (for example, text or image), an ad deliverydimension. Warning: The dimension is incompatible with AD_REQUESTS, MATCH_RATE and IMPRESSION_RPM metrics.

Network report metrics

The following AdSense API metrics are relevant to AdMob data.

AdSense API AdMob API AdMob API Metric Definition
EARNINGS ESTIMATED_EARNINGS The estimated earnings of the AdMob publisher. The currency unit (USD, EUR, or other) of the earning metrics are determined by the localization setting for currency. The amount is in micros. For example, $6.50 would be represented as 6500000.
REACHED_AD_REQUESTS AD_REQUESTS The number of ad requests. The value is an integer.

Note: The metric is incompatible with AD_TYPE dimension.

MATCHED_REACHED_AD_REQUESTS MATCHED_REQUESTS The number of times ads are returned in response to a request. The value is an integer.
VIEWED_IMPRESSIONS IMPRESSIONS The total number of ads shown to users. The value is an integer.
CLICKS CLICKS The number of times a user clicks on an ad. The value is an integer.
REACHED_AD_REQUESTS_MATCH_RATE MATCH_RATE The ratio of matched ad requests over the total ad requests. The value is a double precision (approximate) decimal value.

Note: The metric is incompatible with AD_TYPE dimension.

REACHED_AD_REQUESTS_SHOW_RATE SHOW_RATE The ratio of ads that are displayed over ads that are returned, defined as impressions / matched requests. The value is a double precision (approximate) decimal value.
N/A IMPRESSION_CTR The ratio of clicks over impressions. The value is a double precision (approximate) decimal value.
N/A IMPRESSION_RPM The estimated earnings per thousand ad impressions. The value is in micros. For example, $1.03 would be represented as 1030000.

Note: The metric is incompatible with AD_TYPE dimension.

Time zones

AdSense API AdMob API
Default time zone: Configured in AdSense UI.

Alternate time zone: Configured in AdSense UI.

Default time zone: Configured at time of AdMob account creation.

Alternate time zone: "America/Los_Angeles" is the only supported value at the moment.

Examples

Java

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. Your application will be authorized to access data on behalf of whichever account is currently logged in.

AdSense API

// Load client secrets.
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
    new InputStreamReader(AdSenseSample.class.getResourceAsStream(
        "/client_secrets.json")));
if (clientSecrets.getDetails().getClientId().startsWith("Enter")
    || clientSecrets.getDetails().getClientSecret().startsWith("Enter")) {
  System.out.println("Enter Client ID and Secret from "
      + "https://code.google.com/apis/console/?api=adsense into "
      + "adsense-cmdline-sample/src/main/resources/client_secrets.json");
  System.exit(1);
}

// Set up authorization code flow.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
    JSON_FACTORY, clientSecrets, Collections.singleton(
        "https://www.googleapis.com/auth/adsense.readonly"))
    .setDataStoreFactory(dataStoreFactory).build();

// Authorization.
Credential credential = AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
    .authorize("user");

// Set up AdSense Management API client.
AdSense adsense = new AdSense.Builder(new NetHttpTransport(), JSON_FACTORY, credential)
    .setApplicationName(APPLICATION_NAME).build();

See example in GitHub

AdMob API

// Directory to store user credentials.
private static final java.io.File DATA_STORE_DIR = new java.io.File(
    System.getProperty("user.home"), ".store/admobapi_sample");
private static final HttpTransport HTTP_TRANSPORT = Utils.getDefaultTransport();
private static final JsonFactory JSON_FACTORY = Utils.getDefaultJsonFactory();

// Load client secrets JSON file.
String pathToClientSecretsFile = "INSERT_PATH_TO_CLIENT_SECRETS";
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, 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(
    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, REPORT_SCOPE)
    .setDataStoreFactory(dataStoreFactory).build();

// Build installed application credential.
Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
    .authorize("user");

// Create an AdMob client instance.
AdMob admob = new AdMob.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
    .setApplicationName("admobapi-java-samples").build();

See example in GitHub

List accounts

AdSense API

Accounts accounts = adsense.accounts().list().setMaxResults(maxPageSize)
    .setPageToken(pageToken).execute();

if (accounts.getItems() != null && !accounts.getItems().isEmpty()) {
  for (Account account : accounts.getItems()) {
    System.out.printf("Account with ID \"%s\" and name \"%s\" was found.\n",
        account.getId(), account.getName());
  }
}

See example in GitHub

AdMob API

// Get publisher account which always returns a single account.
ListPublisherAccountsResponse accountsList = adMob.accounts().list().setPageSize(1)
    .execute();

// Display publisher accounts.
for (PublisherAccount account : accountsList.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());
}

See example in GitHub

Generate a network report

AdSense API

// Set date range.
String startDate = "today-7d";
String endDate = "today";
Generate request = adsense.accounts().reports().generate(accountId, startDate, endDate);

// Specify the desired ad client using a filter.
request.setFilter(Arrays.asList("AD_CLIENT_ID==" + escapeFilterParameter(adClientId)));

request.setMetric(Arrays.asList("REACHED_AD_REQUESTS", "CLICKS","VIEWED_IMPRESSIONS",
    "EARNINGS"));
request.setDimension(Arrays.asList("MONTH", "AD_UNIT_SIZE_NAME", "COUNTRY_NAME"));

// Sort by ascending date.
request.setSort(Arrays.asList("+MONTH"));

// Run report.
AdsenseReportsGenerateResponse response = request.execute();
List<List<String>> rows = AdSenseSample.fillMissingDates(response);

if (rows != null && !rows.isEmpty()) {
  // Display headers.
  for (AdsenseReportsGenerateResponse.Headers header : response.getHeaders()) {
    System.out.printf("%25s", header.getName());
  }
  System.out.println();

  // Display results.
  for (List<String> row : rows) {
    for (String column : row) {
      System.out.printf("%25s", column);
    }
    System.out.println();
  }
}

See example in GitHub

AdMob API

String timeZone = "America/Los_Angeles";
Clock clock = Clock.system(ZoneId.of(timeZone));

// Specify date range.
Date startDate = DateUtils.daysBeforeNow(clock, 7);
Date endDate = DateUtils.today(clock);
DateRange dateRange = new DateRange().setStartDate(startDate).setEndDate(endDate);

// Specify metrics.
ImmutableList<String> metrics = ImmutableList.of("AD_REQUESTS","CLICKS","IMPRESSIONS",
    "ESTIMATED_EARNINGS");

// Specify dimensions.
ImmutableList<String> dimensions = ImmutableList.of("MONTH", "FORMAT", "COUNTRY");

// Specify sorting conditions.
List<NetworkReportSpecSortCondition> sortConditions =
    new ArrayList<NetworkReportSpecSortCondition>();
sortConditions.add(new NetworkReportSpecSortCondition().setOrder("ASCENDING")
    .setMetric("MONTH"));

// Create network report specification.
NetworkReportSpec reportSpec = new NetworkReportSpec()
   .setDateRange(dateRange)
   .setTimeZone(timeZone)
   .setMetrics(metrics)
   .setDimensions(dimensions)
   .setSortConditions(sortConditions);

// Create network report request.
GenerateNetworkReportRequest request = new GenerateNetworkReportRequest()
    .setReportSpec(reportSpec);

// Get network report.
/* ACCOUNT_NAME should follow the format "accounts/pub-XXXXXXXXXXXXXXXX" where
* "pub-XXXXXXXXXXXXXXXX" is your publisher ID. See https://support.google.com/admob/answer/2784578
* for instructions on how to find your publisher ID.
*/
InputStream response = adMob.accounts().networkReport().generate(ACCOUNT_NAME, request)
    .executeAsInputStream();

try {
  List<GenerateNetworkReportResponse> result = Arrays.asList(new JsonObjectParser(
      Utils.getDefaultJsonFactory()).parseAndClose(response, StandardCharsets.UTF_8,
      GenerateNetworkReportResponse[].class));
} catch (IOException e) {
  System.out.print(e.getMessage());
}

// Print each record in the response stream.
for (GenerateNetworkReportResponse record : result) {
  System.out.printf("%s%n", record);
}

See example in GitHub

PHP

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. Your application will be authorized to access data on behalf of whichever account is currently logged in.

AdSense API

// Set up authentication.
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');

// Be sure to replace the contents of client_secrets.json with your
// developer credentials.
$client->setAuthConfig('client_secrets.json');

// Create service.
$service = new Google_Service_AdSense($client);

See example in GitHub

AdMob API

// Create an AdMob Client.
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/admob.report');
$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();

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

See example in GitHub

List accounts

AdSense API

// Get list of accounts.
$result = $service->accounts->listAccounts($maxPageSize);
foreach ($accounts as $account) {
    printf("Account with ID \"%s\" and name \"%s\" was found.\n",
        $account['id'], $account['name']);
}

See example in GitHub

AdMob API

// Get list of accounts.
$result = $service->accounts->listAccounts();
$accounts = $result->account;

// Print account information.
foreach ($accounts as $account) {
    printf("
        Account Name: '%s' \n
        Publisher Id: '%s' \n
        Currency Code: '%s' \n
        Reporting Time Zone: '%s' \n",
        $account->getName(),
        $account->getPublisherId(),
        $account->getCurrencyCode(),
        $account->getReportingTimezone()
    );
}

See example in GitHub

Generate a network report

AdSense API

// Set date range.
$startDate = 'today-7d';
$endDate = 'today-1d';

$optParams = array(
    'metric' => array('REACHED_AD_REQUESTS', 'CLICKS',
        'VIEWED_IMPRESSIONS', 'EARNINGS'),
    'dimension' => array('MONTH', 'AD_UNIT_SIZE_NAME', 'COUNTRY_NAME'),
    'sort' => '+MONTH',
    'filter' => array(
        'AD_CLIENT_ID==' . $adClientId
    )
);

// Run report.
$report = $service->accounts_reports->generate($accountId, $startDate,
    $endDate, $optParams);

if (isset($report) && isset($report['rows'])) {
    // Display headers.
    foreach($report['headers'] as $header) {
        printf('%25s', $header['name']);
    }
    print "\n";

    // Display results.
    foreach($report['rows'] as $row) {
        foreach($row as $column) {
            printf('%25s', $column);
        }
        print "\n";
    }
}

See example in GitHub

AdMob API

$startDate = DateUtils::oneWeekBeforeToday();
$endDate = DateUtils::today();

// Specify date range.
$dateRange = new \Google_Service_AdMob_DateRange();
$dateRange->setStartDate($startDate);
$dateRange->setEndDate($endDate);

// Specify sorting conditions.
$sortConditions = new
    \Google_Service_AdMob_NetworkReportSpecSortCondition();
$sortConditions->setOrder('ASCENDING');
$sortConditions->setDimension('MONTH');

// Create network report specification.
$reportSpec = new \Google_Service_AdMob_NetworkReportSpec();
$reportSpec->setMetrics(['AD_REQUESTS','CLICKS', 'IMPRESSIONS',
    'ESTIMATED_EARNINGS']);
$reportSpec->setDimensions(['MONTH', 'FORMAT',
    'COUNTRY']);
$reportSpec->setDateRange($dateRange);

// Create network report request.
$networkReportRequest = new
    \Google_Service_AdMob_GenerateNetworkReportRequest();
$networkReportRequest->setReportSpec($reportSpec);

// Generate network report.
// Get AdMob account information by replacing accountName,
// which follows the format "accounts/pub-XXXXXXXXXXXXXXXX".
// See https://support.google.com/admob/answer/2784578
// for instructions on how to find your publisher ID.
$networkReportResponse = $service->accounts_networkReport->generate(
    $accountName,
    $networkReportRequest
);

// Convert network report response to a simple object.
$networkReportResponse = $networkReportResponse->tosimpleObject();

// Print each record in the report.
foreach ($networkReportResponse as $record) {
    printf("'%s' \n", json_encode($record));
}

See example in GitHub

Python

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. Your application will be authorized to access data on behalf of whichever account is currently logged in.

AdSense API

import argparse
import sys

from adsense_util import get_account_id
from adsense_util_data_collator import DataCollator
from apiclient import sample_tools
from oauth2client import client

service, flags = sample_tools.init(
    'adsense', 'v1.4', __doc__, __file__, parents=[],
    scope='https://www.googleapis.com/auth/adsense.readonly')

See example in GitHub

AdMob API

This example uses the new python authentication library.

import os

from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from google.auth.transport.requests import Request

...

# Authenticate using the client_secrets file.
client_secrets = os.path.join(
    os.path.dirname(__file__), 'client_secrets.json')
flow = Flow.from_client_secrets_file(
    client_secrets,
    scopes=['https://www.googleapis.com/auth/admob.report'],
    redirect_uri='urn:ietf:wg:oauth:2.0:oob')

# Redirect the user to auth_url on your platform.
auth_url, _ = flow.authorization_url()
print('Please go to this URL: {}\n'.format(auth_url))

# The user will get an authorization code. This code is used to get the
# access token.
code = input('Enter the authorization code: ')
flow.fetch_token(code=code)
credentials = flow.credentials

// Create an AdMob service object on which to run the requests.
admob = build('admob', 'v1', credentials=credentials)

See example in GitHub

List accounts

AdSense API

# Retrieve account list in pages and display data as we receive it.
request = service.accounts().list(maxResults=MAX_PAGE_SIZE)

while request is not None:
  result = request.execute()
  accounts = result['items']
  for account in accounts:
    print (
        'Account with ID "%s" and name "%s" was found. '
        % (account['id'], account['name']))

request = service.accounts().list_next(request, result)

See example in GitHub

AdMob API

# Gets and lists AdMob accounts. The list will always return a single
# account.
result = admob.accounts().list().execute()

# Print the result.
account_list = result['account']
for account in account_list:
  print('Name: ' + account_list['name'])
  print('Publisher ID: ' + account_list['publisherId'])
  print('Currency code: ' + account_list['currencyCode'])
  print('Reporting time zone: ' + account_list['reportingTimeZone'])

See example in GitHub

Generate a network report

AdSense API

// Generate report.
result = service.accounts().reports().generate(
    accountId=account_id,
    startDate='2020-1-1',
    endDate='2020-3-1',
    metric=['REACHED_AD_REQUESTS','CLICKS', 'VIEWED_IMPRESSIONS',
        'EARNINGS'],
    dimension=['MONTH', 'AD_UNIT_SIZE_NAME', 'COUNTRY_NAME'],
    sort=['+MONTH']).execute()

result = DataCollator([result]).collate_data()

# Display headers.
for header in result['headers']:
  print '%25s' % header['name'],
print

# Display results.
for row in result['rows']:
  for column in row:
    print '%25s' % column
  print

# Display date range.
print 'Report from %s to %s.' % (result['startDate'], result['endDate'])

See example in GitHub

AdMob API

// Set date range
date_range = {
    'startDate': {'year': 2020, 'month': 1, 'day': 1},
    'endDate': {'year': 2020, 'month': 3, 'day': 1}
}

# Set metrics.
metrics = ['AD_REQUESTS','CLICKS', 'IMPRESSIONS', 'ESTIMATED_EARNINGS']

# Set dimensions.
dimensions = ['MONTH', 'FORMAT', 'COUNTRY']

# Set sort conditions.
sort_conditions = {'dimension': 'MONTH', 'order': 'ASCENDING'}

# Create network report specifications.
report_spec = {
    'dateRange': date_range,
    'dimensions': dimensions,
    'metrics': metrics,
    'sortConditions': [sort_conditions]
}

# Create network report request.
request = {'reportSpec': report_spec}

# Execute network report request.
# Get AdMob account information by replacing publisher_id,
# which follows the format "pub-XXXXXXXXXXXXXXXX".
# See https://support.google.com/admob/answer/2784578
# for instructions on how to find your publisher ID.
result = admob.accounts().networkReport().generate(
    parent='accounts/{}'.format(publisher_id), body=request).execute()

# Display results.
for report_line in result:
  print(report_line)

See example in GitHub