Get started with the AdMob API

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

Prerequisites

Create a project

To get started using the AdMob API, 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 automatically.

Generate credentials

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

The following instructions guide you through the process of creating an OAuth 2.0 client ID to use with the installed app 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.

    1. If you hadn't configured an OAuth consent screen for this project previously, you'll be directed to do so now. Click CONFIGURE CONSENT SCREEN.

    2. Select the user type and click CREATE.

    3. Fill out the initial form. You can edit this later if needed. Click Save when done.

    4. Navigate back to Credentials > CREATE CREDENTIALS > OAuth client ID to continue.

  4. Select Desktop app as the application type, give it a name, then 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

The AdMob API 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.

With OAuth 2.0 credentials created, you're ready to start using the AdMob API. To request access using OAuth 2.0, your application will also need the scope information.

Here's the OAuth 2.0 scope information:

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

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

Java client library

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

    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.util.Utils;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.util.store.DataStoreFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.services.admob.v1.AdMob;
    
    ...
    
    /** 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");
    
  2. Create an authorized AdMob client.

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

    import com.google.api.services.admob.v1.AdMob;
    import com.google.api.services.admob.v1.model.PublisherAccount;
    
    ...
    
    // Get publisher account.
    /* 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.
     */
    private static final String ACCOUNT_NAME = "accounts/pub-XXXXXXXXXXXXXXXX";
    
    PublisherAccount account = adMob.accounts().get(ACCOUNT_NAME).execute();
    
    // Display publisher account information.
    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());
    
  4. Generate a network report.

    import com.google.api.client.googleapis.util.Utils;
    import com.google.api.client.json.JsonObjectParser;
    import com.google.api.services.admob.v1.AdMob;
    import com.google.api.services.admob.v1.model.Date;
    import com.google.api.services.admob.v1.model.DateRange;
    import com.google.api.services.admob.v1.model.GenerateNetworkReportRequest;
    import com.google.api.services.admob.v1.model.GenerateNetworkReportResponse;
    import com.google.api.services.admob.v1.model.NetworkReportSpec;
    import com.google.api.services.samples.admob.util.DateUtils;
    import com.google.common.collect.ImmutableList;
    import java.io.InputStream;
    
    ...
    
    /* AdMob API only supports the account default timezone and "America/Los_Angeles", see
     * https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.networkReport/generate
     * for more information.
     */
    String timeZone = "America/Los_Angeles";
    Clock clock = Clock.system(ZoneId.of(timeZone));
    
    // Specify date range.
    Date startDate = DateUtils.daysBeforeNow(clock, 30);
    Date endDate = DateUtils.today(clock);
    DateRange dateRange = new DateRange().setStartDate(startDate).setEndDate(endDate);
    
    // Specify metrics.
    ImmutableList<String> metrics = ImmutableList.of("IMPRESSIONS", "MATCH_RATE");
    
    // Specify dimensions.
    ImmutableList<String> dimensions = ImmutableList.of("FORMAT", "AD_UNIT");
    
    // Create network report specification.
    NetworkReportSpec reportSpec =
        new NetworkReportSpec()
            .setDateRange(dateRange)
            .setTimeZone(timeZone)
            .setMetrics(metrics)
            .setDimensions(dimensions);
    
    // 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);
    }
    

PHP client library

Requests using PHP client library

  1. Load the client secrets file and 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. 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 AdMob service object on which to run the requests.
    $service = new Google_Service_AdMob($client);
    
  3. Get account info.

    // 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.
    $service->accounts->get($accountName);
    
    // Print account information.
    printf("
      Account Name: \"%s\" \n
      Publisher Id: \"%s\" \n
      Currency Code: \"%s\" \n
      Reporting Time Zone: \"%s\" \n",
        $result->getName(),
        $result->getPublisherId(),
        $result->getCurrencyCode(),
        $result->getReportingTimezone());
    
  4. Generate a network report.

    /**
     * AdMob API only supports the account default timezone and
     * "America/Los_Angeles", see
     * https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.mediationReport/generate
     * for more information.
     */
    $startDate = DateUtils::oneWeekBeforeToday();
    $endDate = DateUtils::today();
    
    // Specify date range.
    $dateRange = new \Google_Service_AdMob_DateRange();
    $dateRange->setStartDate($startDate);
    $dateRange->setEndDate($endDate);
    
    // Create network report specification.
    $reportSpec = new \Google_Service_AdMob_NetworkReportSpec();
    $reportSpec->setMetrics(['IMPRESSIONS', 'MATCH_RATE']);
    $reportSpec->setDimensions(['FORMAT', 'AD_UNIT']);
    $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));
    }
    

Python client library

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

    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
    
  2. Create an AdMob service object.

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

    # 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().get(
    name='accounts/{}'.format(publisher_id)).execute()
    
    # Print the result.
    print('Name: ' + result['name'])
    print('Publisher ID: ' + result['publisherId'])
    print('Currency code: ' + result['currencyCode'])
    print('Reporting time zone: ' + result['reportingTimeZone'])
    
  4. Generate a network report.

    # Set date range.
    # AdMob API only supports the account default timezone and "America/Los_Angeles", see
    # https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.networkReport/generate
    # for more information.
    date_range = {
        'startDate': {'year': 2020, 'month': 1, 'day': 1},
        'endDate': {'year': 2020, 'month': 3, 'day': 30}
    }
    
    # Set metrics.
    metrics = ['IMPRESSIONS', 'MATCH_RATE']
    
    # Set dimensions.
    dimensions = ['FORMAT', 'AD_UNIT', 'COUNTRY']
    
    # Set sort conditions.
    sort_conditions = {'dimension': 'MATCH_RATE', 'order': 'DESCENDING'}
    
    # Set dimension filters.
    dimension_filters = {
        'dimension': 'COUNTRY',
        'matchesAny': {
            'values': ['US', 'CA']
        }
    }
    
    # Create network report specifications.
    report_spec = {
        'dateRange': date_range,
        'dimensions': dimensions,
        'metrics': metrics,
        'sortConditions': [sort_conditions],
        'dimensionFilters': [dimension_filters]
    }
    
    # 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)
    

curl (command line)

Requests using curl

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

    For authentication and authorization, we recommend using oauth2l, a simple command-line tool for working with Google OAuth 2.0. Install oauth2l and run the command below, replacing path_to_credentials_json with a path to a credentials.json file that you download when registering your cloud application. For the first run, the command walks you through the OAuth 2.0 authorization flow. Subsequent runs refresh the token automatically.

    oauth2l header --json path_to_credentials_json \
            https://www.googleapis.com/auth/admob.report
    
  2. Get account info.

    Get AdMob account information by replacing pub-XXXXXXXXXXXXXXXX with your publisher ID. See the instructions on how to find your publisher ID.

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

    Sample response:

    {
     "account": [
       {
         "publisherId": "pub-XXXXXXXXXXXXXXXX",
         "name:": "accounts/pub-XXXXXXXXXXXXXXXX",
         "reportingTimeZone": "Europe/Paris",
         "currencyCode": "EUR"
       }
     ]
    }
    
  3. 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 as part of the request URI (for example, v1/accounts/pub-XXXXXXXXXXXXXXXX/networkReport:generate).

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

    curl -X POST \
              https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/networkReport:generate \
           -H "$(oauth2l header --json path_to_credentials_json \
           -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"
     }
    }]