### AdMob API v1 - PHP Client Setup and Authentication Source: https://developers.google.com/admob/api/v1/reporting This section details how to set up the Google API client library for PHP, authenticate with the AdMob API, and create an authorized AdMob client. ```APIDOC ## AdMob API v1 - PHP Client Setup and Authentication ### Description This section details how to set up the Google API client library for PHP, authenticate with the AdMob API, 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 logged in. ### Method N/A (Client-side setup) ### Endpoint N/A (Client-side setup) ### Parameters N/A ### Request Example ```php // Create an AdMob Client. $client = new Google_Client(); $client->addScope('https://www.googleapis.com/auth/admob.readonly'); $client->setApplicationName('AdMob API Quickstart'); $client->setAccessType('offline'); // Be sure to replace the content 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(); ``` ### Response N/A (Client-side setup) ``` -------------------------------- ### AdMob API Authentication Setup (Python) Source: https://developers.google.com/admob/api/v1/reporting Sets up authentication credentials for the AdMob API using OAuth 2.0. This involves defining constants for the redirect URI, client secrets file, API name, version, and scope. It prepares the application for user authorization, which requires a browser prompt on the first run. ```Python PORT = 8080 REDIRECT_URI = f"http://127.0.0.1:{PORT}" # This variable specifies the name of a file that contains the OAuth 2.0 # information for this application, including its client_id and client_secret. CLIENT_SECRETS_FILE = "client_secrets.json" # Default OAuth 2.0 access parameters. # # These parameters allow for full read access to the authenticated user's AdMob # account and requires requests to use an SSL connection. API_NAME = "admob" API_VERSION = "v1" API_SCOPE = "https://www.googleapis.com/auth/admob.readonly" ``` -------------------------------- ### List AdMob Apps (Python) Source: https://developers.google.com/admob/api/v1/app-ad-units_hl=id This example shows how to list all applications associated with an AdMob account. It handles pagination to retrieve all apps, even if there are more than the page size allows. The output includes app details such as ID, platform, name, and store information. ```python next_page_token = '' while True: response = service.accounts().apps().list( pageSize=PAGE_SIZE, pageToken=next_page_token, parent='accounts/{}'.format(publisher_id)).execute() if not response: break apps = response['apps'] for app in apps: print('App ID: ' + app['appId']) print('App Platform: ' + app['platform']) print('App Name: ' + app['name']) if 'linkedAppInfo' in app: linked_app_info = app['linkedAppInfo'] print('App Store ID: ' + linked_app_info['appStoreId']) print('App Store Display Name: ' + linked_app_info['displayName']) if 'manualAppInfo' in app: manual_app_info = app['manualAppInfo'] print('App Manual Info: ' + manual_app_info['displayName']) if 'nextPageToken' not in response: break next_page_token = response['nextPageToken'] ``` -------------------------------- ### List AdMob Apps (Java) Source: https://developers.google.com/admob/api/v1/reporting_hl=id Lists all applications associated with an AdMob account using the AdMob API. This example handles pagination to retrieve all apps, even if they exceed the initial page size. It prints details such as app name, ID, platform, and store information. Input is an AdMob client instance. ```java // Defines maximum size page to retrieve. A smaller page size will require more API requests, see // inventory quota limits at https://developers.google.com/admob/api/quotas. private static final Integer PAGE_SIZE = 1000; public static void runExample(AdMob adMob) throws Exception { ListAppsResponse response; String nextPageToken = null; do { // Create and execute the apps list request. response = adMob .accounts() .apps() .list(ACCOUNT_NAME) .setPageSize(PAGE_SIZE) .setPageToken(nextPageToken) .execute(); // Display apps. List apps = response.getApps(); for (App app : apps) { AppLinkedAppInfo linkedAppInfo = app.getLinkedAppInfo(); System.out.printf( "App Name: %s, " + "App ID: %s, " + "App Platform: %s, " + "App Store ID: %s, " + "App Store Display Name: %s, " + "App Manual Info: %s%n", app.getName(), app.getAppId(), app.getPlatform(), linkedAppInfo == null ? "" : linkedAppInfo.getAppStoreId(), linkedAppInfo == null ? "" : linkedAppInfo.getDisplayName(), app.getManualAppInfo().getDisplayName()); } // Update the next page token. nextPageToken = response.getNextPageToken(); } while (nextPageToken != null); } ``` -------------------------------- ### Get AdMob Account Information (PHP) Source: https://developers.google.com/admob/api/v1/reporting_hl=hi This example retrieves and prints account details using the AdMob service object. It fetches information such as the account name, publisher ID, currency code, and reporting time zone. The function expects a valid account name string. ```php // Get account. $result = $service->accounts->get($accountName); // Print account information. if (!empty($result)) { printf( "\n 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() ); } else { print "No accounts found.\n"; } ``` -------------------------------- ### GET /v1beta/{parent=accounts/*/adSources/*}/adapters Source: https://developers.google.com/admob/api/v1/reference/rest List the adapters of the ad source. ```APIDOC ## GET /v1beta/{parent=accounts/*/adSources/*}/adapters ### Description List the adapters of the ad source. ### Method GET ### Endpoint /v1beta/{parent=accounts/*/adSources/*}/adapters ### Parameters #### Path Parameters - **parent** (string) - Required - The ad source which the adapters belong to. Format: `accounts/{publisher_id}/adSources/{ad_source_id}`. #### Query Parameters #### Request Body ### Request Example ### Response #### Success Response (200) - **adapters** (array) - The list of adapters. #### Response Example ``` -------------------------------- ### GET /v1beta/{name=accounts/*} Source: https://developers.google.com/admob/api/v1/reference/rest Gets information about the specified AdMob publisher account. ```APIDOC ## GET /v1beta/{name=accounts/*} ### Description Gets information about the specified AdMob publisher account. ### Method GET ### Endpoint /v1beta/{name=accounts/*} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the AdMob publisher account to get. Example: `accounts/0000000000000000000` #### Query Parameters #### Request Body ### Request Example ### Response #### Success Response (200) - **name** (string) - The resource name of the AdMob publisher account, which is in the format `accounts/{publisher_id}`. - **publisherId** (string) - The AdMob publisher ID which is a unique 10-digit number generated by AdMob. - **timestamp** (string) - The timestamp when the account was created. #### Response Example ``` -------------------------------- ### GET /v1beta/{parent=accounts/*}/adSources Source: https://developers.google.com/admob/api/v1/reference/rest List the ad sources. ```APIDOC ## GET /v1beta/{parent=accounts/*}/adSources ### Description List the ad sources. ### Method GET ### Endpoint /v1beta/{parent=accounts/*}/adSources ### Parameters #### Path Parameters - **parent** (string) - Required - The AdMob account which the ad sources belong to. Format: `accounts/{publisher_id}`. #### Query Parameters #### Request Body ### Request Example ### Response #### Success Response (200) - **adSources** (array) - The list of ad sources. #### Response Example ``` -------------------------------- ### AdMob API Third-Party Integration Guide Source: https://developers.google.com/admob/api/v1/third-party Overview of third-party integration with the AdMob API, including authentication and support resources. ```APIDOC ## AdMob API Third-Party Integration ### Description This guide provides best practices, tips, and tricks for third-party integrations with the AdMob API. To use the AdMob API as a third party to access a publisher's data, no additional Google approval is required, but you must agree to the AdMob API terms and conditions. ### Authentication: Accessing Client AdMob Data Securely setting up your authentication workflow is necessary for your application to access your client's AdMob data. All requests to the AdMob API must be authorized. #### Prerequisites * A Google Account. * Familiarity with REST basics and authorizing requests with OAuth 2.0. #### Complete Authorization Steps Follow the steps to complete your authorization setup. This typically involves obtaining credentials and handling OAuth 2.0 flows to access client data. ### Keeping Up-to-Date with the API It's important to stay informed about API version changes, deprecations, and new releases. Subscribe to the Ads Developer Blog for announcements. ### Getting Support If you encounter issues with your AdMob API integration, post your questions to the AdMob API developer forum. ``` -------------------------------- ### Get AdMob Account Information (Java) Source: https://developers.google.com/admob/api/v1/reporting This example demonstrates how to retrieve publisher account information using the AdMob client. It requires the account name formatted as "accounts/pub-XXXXXXXXXXXXXXXX" and outputs the publisher's name, ID, currency code, and reporting time zone. ```java /* 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"; public static void runExample(AdMob adMob, String accountName) throws Exception { // Get publisher account. PublisherAccount account = adMob.accounts().get(accountName).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()); } ``` -------------------------------- ### AdMob API V1 - Java Client Library Setup and Authentication Source: https://developers.google.com/admob/api/v1/app-ad-units This section details the initial steps for using the AdMob API with the Java client library. It includes loading client secrets, setting up the authorization code flow, and obtaining authorized credentials for your application. ```APIDOC ## AdMob API V1 - Java Client Library Setup and Authentication ### Description This process outlines how to authenticate your Java application with the AdMob API using OAuth 2.0. It involves loading client secrets, defining authorization scopes, and handling the user authorization flow to obtain credentials. ### Method N/A (Client-side library usage) ### Endpoint N/A (Client-side library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java 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; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ImmutableSet; // ... other imports /** 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 READONLY_SCOPE = ImmutableSet.of("https://www.googleapis.com/auth/admob.readonly"); DataStoreFactory dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR); GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, READONLY_SCOPE) .setDataStoreFactory(dataStoreFactory) .build(); // Build installed application credential. Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); ``` ### Response #### Success Response (200) N/A (Client-side library usage) #### Response Example N/A (Client-side library usage) ``` -------------------------------- ### GET /accounts/{publisherId} Source: https://developers.google.com/admob/api/v1/reporting Retrieves AdMob account information for a given publisher ID. ```APIDOC ## Get Account Info ### Description Retrieves AdMob account information, including publisher ID, account name, reporting time zone, and currency code. ### Method GET ### Endpoint `/v1/accounts/{publisherId}` ### Parameters #### Path Parameters - **publisherId** (string) - Required - Your AdMob publisher ID (e.g., `pub-XXXXXXXXXXXXXXXX`). ### Request Example ```bash 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.readonly)" ``` ### Response #### Success Response (200) - **account** (array) - Contains account details. - **publisherId** (string) - The publisher ID. - **name** (string) - The account resource name. - **reportingTimeZone** (string) - The reporting time zone for the account. - **currencyCode** (string) - The default currency code for the account. #### Response Example ```json { "account": [ { "publisherId": "pub-XXXXXXXXXXXXXXXX", "name": "accounts/pub-XXXXXXXXXXXXXXXX", "reportingTimeZone": "Europe/Paris", "currencyCode": "EUR" } ] } ``` ``` -------------------------------- ### GET /accounts/{publisherId}/apps Source: https://developers.google.com/admob/api/v1/reporting Lists all apps associated with a given AdMob publisher ID. ```APIDOC ## List Apps ### Description Retrieves a list of all AdMob apps associated with your publisher account. ### Method GET ### Endpoint `/v1/accounts/{publisherId}/apps` ### Parameters #### Path Parameters - **publisherId** (string) - Required - The publisher ID for which to list apps. ### Request Example ```bash curl -X GET https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/apps \ -H "Content-Type: application/json" \ -H "$(oauth2l header --json path_to_credentials_json \ https://www.googleapis.com/auth/admob.readonly)" ``` ### Response #### Success Response (200) - **app** (array) - A list of AdMob apps. - **name** (string) - The resource name of the app. - **appId** (string) - The AdMob App ID. - **platform** (string) - The platform of the app (e.g., `"ANDROID"`, `"IOS"`). - **manualAppInfo** (object) - Manual information about the app. - **displayName** (string) - The display name of the app. - **linkedAppInfo** (object) - Information about the app linked to app stores. - **appStoreId** (string) - The ID of the app in the app store. - **displayName** (string) - The display name of the app from the app store. #### Response Example ```json { "app": [ { "name": "accounts/pub-XXXXXXXXXXXXXXXX/apps/XXXXXXXXXX", "appId": "ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX", "platform": "ANDROID", "manualAppInfo": { "displayName": "Example App" }, "linkedAppInfo": { "appStoreId": "com.example.myApp", "displayName": "Example App" } } ] } ``` ``` -------------------------------- ### GET /accounts/{publisherId}/adUnits Source: https://developers.google.com/admob/api/v1/reporting Lists all ad units associated with a given AdMob publisher ID. ```APIDOC ## List Ad Units ### Description Retrieves a list of all AdMob ad units associated with your publisher account. ### Method GET ### Endpoint `/v1/accounts/{publisherId}/adUnits` ### Parameters #### Path Parameters - **publisherId** (string) - Required - The publisher ID for which to list ad units. ### Request Example ```bash curl -X GET https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/adUnits \ -H "Content-Type: application/json" \ -H "$(oauth2l header --json path_to_credentials_json \ https://www.googleapis.com/auth/admob.readonly)" ``` ### Response #### Success Response (200) - **adUnit** (array) - A list of AdMob ad units. - **name** (string) - The resource name of the ad unit. - **adUnitId** (string) - The AdMob Ad Unit ID. - **appId** (string) - The AdMob App ID the ad unit belongs to. - **displayName** (string) - The display name of the ad unit. - **adFormat** (string) - The format of the ad unit (e.g., `"REWARDED"`, `"BANNER"`). - **adTypes** (array of strings) - The types of ads supported by the ad unit. #### Response Example ```json { "adUnit": [ { "name": "accounts/pub-XXXXXXXXXXXXXXXX/adUnits/XXXXXXXXXX", "adUnitId": "ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX", "appId": "ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX", "displayName": "AdMob Rewarded", "adFormat": "REWARDED", "adTypes": ["RICH_MEDIA", "VIDEO"] } ] } ``` ``` -------------------------------- ### POST /v1beta/{parent=accounts/*}/adUnitMappings:batchCreate Source: https://developers.google.com/admob/api/v1/reference/rest Batch create the ad unit mappings under the specific AdMob account. ```APIDOC ## POST /v1beta/{parent=accounts/*}/adUnitMappings:batchCreate ### Description Batch create the ad unit mappings under the specific AdMob account. ### Method POST ### Endpoint /v1beta/{parent=accounts/*}/adUnitMappings:batchCreate ### Parameters #### Path Parameters - **parent** (string) - Required - The AdMob account under which to create the ad unit mappings. Format: `accounts/{publisher_id}`. #### Query Parameters #### Request Body - **adUnitMappings** (array) - Required - The ad unit mappings to create. - **adUnitId** (string) - Required - The ID of the ad unit to associate with the mapping. - **adSourceName** (string) - Required - The display name of the ad source. - **adSourceId** (string) - Optional - The ID of the ad source. ### Request Example ```json { "adUnitMappings": [ { "adUnitId": "1234567890", "adSourceName": "AdMob Network", "adSourceId": "1111111111" } ] } ``` ### Response #### Success Response (200) - **adUnitMappings** (array) - The created ad unit mappings. #### Response Example ```json { "adUnitMappings": [ { "adUnitId": "1234567890", "adSourceName": "AdMob Network", "adSourceId": "1111111111" } ] } ``` ``` -------------------------------- ### Get Account Info Source: https://developers.google.com/admob/api/v1/reporting Retrieves and prints information about the AdMob account associated with the provided publisher ID. ```APIDOC ## GET /v1/accounts/{publisherId} ### Description Retrieves details for a specific AdMob account using its publisher ID. ### Method GET ### Endpoint /v1/accounts/{publisherId} ### Parameters #### Path Parameters - **publisherId** (string) - Required - The AdMob publisher ID (e.g., "pub-XXXXXXXXXXXXXXXX"). #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'admob' is an initialized AdMob service object and 'PUBLISHER_ID' is set response = admob.accounts().get(name='accounts/{}'.format(PUBLISHER_ID)).execute() ``` ### Response #### Success Response (200) - **name** (string) - The resource name of the account. - **publisherId** (string) - The publisher ID of the account. - **currencyCode** (string) - The currency code used for reporting. - **reportingTimeZone** (string) - The reporting time zone of the account. #### Response Example ```json { "name": "accounts/1234567890", "publisherId": "1234567890", "currencyCode": "USD", "reportingTimeZone": "America/Los_Angeles" } ``` ``` -------------------------------- ### List Applications using AdMob API v1 (Java) Source: https://developers.google.com/admob/api/v1/reporting_hl=pl Lists all applications associated with an AdMob account. This method handles pagination to retrieve all apps, displaying key details such as App Name, App ID, Platform, App Store ID, and Display Name. It uses a page size of 1000 and retrieves the next page token until all applications are listed. Dependencies include Google API client libraries. ```java // Defines maximum size page to retrieve. A smaller page size will require more API requests, see // inventory quota limits at https://developers.google.com/admob/api/quotas. private static final Integer PAGE_SIZE = 1000; public static void runExample(AdMob adMob) throws Exception { ListAppsResponse response; String nextPageToken = null; do { // Create and execute the apps list request. response = adMob .accounts() .apps() .list(ACCOUNT_NAME) // ACCOUNT_NAME needs to be defined elsewhere .setPageSize(PAGE_SIZE) .setPageToken(nextPageToken) .execute(); // Display apps. List apps = response.getApps(); for (App app : apps) { AppLinkedAppInfo linkedAppInfo = app.getLinkedAppInfo(); System.out.printf( "App Name: %s, " + "App ID: %s, " + "App Platform: %s, " + "App Store ID: %s, " + "App Store Display Name: %s, " + "App Manual Info: %s%n", app.getName(), app.getAppId(), app.getPlatform(), linkedAppInfo == null ? "" : linkedAppInfo.getAppStoreId(), linkedAppInfo == null ? "" : linkedAppInfo.getDisplayName(), app.getManualAppInfo().getDisplayName()); } // Update the next page token. nextPageToken = response.getNextPageToken(); } while (nextPageToken != null); } ``` -------------------------------- ### Get AdMob Account Info using curl Source: https://developers.google.com/admob/api/v1/reporting Retrieves AdMob account information using a curl GET request. Requires your publisher ID and a valid authorization header generated by oauth2l. The response includes account details like publisher ID, name, reporting time zone, and currency code. ```shell 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.readonly)" ``` -------------------------------- ### AdMob API v1 - Get Account Information Source: https://developers.google.com/admob/api/v1/reporting This endpoint retrieves information about a specific AdMob account, including its name, publisher ID, currency code, and reporting time zone. ```APIDOC ## AdMob API v1 - Get Account Information ### Description This endpoint retrieves information about a specific AdMob account, including its name, publisher ID, currency code, and reporting time zone. ### Method GET ### Endpoint `/v1/accounts/{accountName}` ### Parameters #### Path Parameters - **accountName** (string) - Required - The name of the account, which follows the format "accounts/pub-XXXXXXXXXXXXXXXX". ### Request Example ```php // Get account. $result = $service->accounts->get($accountName); ``` ### Response #### Success Response (200) - **name** (string) - The name of the account. - **publisherId** (string) - The publisher ID of the AdMob account. - **currencyCode** (string) - The currency code used for the account. - **reportingTimezone** (string) - The reporting time zone for the account. #### Response Example ```json { "name": "accounts/pub-1234567890123456", "publisherId": "1234567890123456", "currencyCode": "USD", "reportingTimezone": "America/Los_Angeles" } ``` ``` -------------------------------- ### AdMob API V1 - Create Authorized AdMob Client Source: https://developers.google.com/admob/api/v1/app-ad-units After obtaining authorized credentials, this step demonstrates how to create an instance of the AdMob client using the provided HTTP transport, JSON factory, and credentials. ```APIDOC ## AdMob API V1 - Create Authorized AdMob Client ### Description This section explains how to instantiate the AdMob service client after successful authentication. The client is configured with application-specific details. ### Method N/A (Client-side library usage) ### Endpoint N/A (Client-side library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Assuming 'credential' is an authenticated Credential object from the previous step // Assuming 'HTTP_TRANSPORT' and 'JSON_FACTORY' are initialized // Create an AdMob client instance. AdMob admob = new AdMob.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) .setApplicationName("admobapi-java-samples") .build(); ``` ### Response #### Success Response (200) N/A (Client-side library usage) #### Response Example N/A (Client-side library usage) ``` -------------------------------- ### Python: Authenticate and Generate Credentials Source: https://developers.google.com/admob/api/v1/app-ad-units This snippet shows how to set up authentication for the AdMob API using the Python client library. It utilizes `google-auth-oauthlib` to handle the OAuth 2.0 flow and generate authorization credentials. ```python 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.readonly'], 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: {} '.format(auth_url)) # The user will get an authorization code. This code is used to get the ``` -------------------------------- ### Get AdMob Account Information Source: https://developers.google.com/admob/api/v1/reporting_hl=tr Retrieves and prints detailed information about an AdMob account, including its name, publisher ID, currency code, and reporting time zone. Requires the AdMob service object and the publisher ID. ```python PUBLISHER_ID = 'pub-XXXXXXXXXXXXXXXX' # Replace with your actual publisher ID def get_account(service, publisher_id): """Gets and prints an AdMob account. Args: service: An AdMob Service Object. publisher_id: An ID that identifies the publisher. """ try: response = service.accounts().get( name='accounts/{}'.format(publisher_id)).execute() print('Name: ' + response.get('name', 'N/A')) print('Publisher ID: ' + response.get('publisherId', 'N/A')) print('Currency code: ' + response.get('currencyCode', 'N/A')) print('Reporting time zone: ' + response.get('reportingTimeZone', 'N/A')) except Exception as e: print(f"An error occurred: {e}") ``` -------------------------------- ### List AdMob Apps using curl Source: https://developers.google.com/admob/api/v1/reporting Lists all AdMob apps associated with your publisher account using a curl GET request. It requires your publisher ID and a valid authorization header. The response includes a list of apps with their names, IDs, platforms, and display information. ```shell curl -X GET https://admob.googleapis.com/v1/accounts/pub-XXXXXXXXXXXXXXXX/apps \ -H "Content-Type: application/json" \ -H "$(oauth2l header --json path_to_credentials_json \ https://www.googleapis.com/auth/admob.readonly)" ``` -------------------------------- ### List Apps using AdMob API v1 in Java Source: https://developers.google.com/admob/api/v1/app-ad-units This snippet demonstrates how to list all apps associated with an AdMob account. It handles pagination to retrieve all apps and prints details for each app. Requires an authenticated AdMob client and ACCOUNT_NAME. ```java ListAppsResponse response; String nextPageToken = null; // Define ACCOUNT_NAME and PAGE_SIZE appropriately before this block. // For example: final String ACCOUNT_NAME = "accounts/YOUR_ACCOUNT_ID"; // final int PAGE_SIZE = 100; do { // Create and execute the apps list request. response = adMob .accounts() .apps() .list(ACCOUNT_NAME) .setPageSize(PAGE_SIZE) .setPageToken(nextPageToken) .execute(); // Display apps. List apps = response.getApps(); if (apps != null) { for (App app : apps) { AppLinkedAppInfo linkedAppInfo = app.getLinkedAppInfo(); System.out.printf( "App Name: %s, " + "App ID: %s, " + "App Platform: %s, " + "App Store ID: %s, " + "App Store Display Name: %s, " + "App Manual Info: %s%n", app.getName(), app.getAppId(), app.getPlatform(), linkedAppInfo == null ? "" : linkedAppInfo.getAppStoreId(), linkedAppInfo == null ? "" : linkedAppInfo.getDisplayName(), app.getManualAppInfo() != null ? app.getManualAppInfo().getDisplayName() : ""); } } // Update the next page token. nextPageToken = response.getNextPageToken(); } while (nextPageToken != null && !nextPageToken.isEmpty()); ``` -------------------------------- ### List Ad Units using AdMob API v1 (Java) Source: https://developers.google.com/admob/api/v1/reporting_hl=pl Lists all ad units within an AdMob account. This method handles pagination, retrieving ad units in batches of 1000. It continues fetching subsequent pages using the next page token until all ad units are retrieved. Dependencies include Google API client libraries. ```java // Defines maximum size page to retrieve. A smaller page size will require more API requests, see // inventory quota limits at https://developers.google.com/admob/api/quotas. private static final Integer PAGE_SIZE = 1000; public static void runExample(AdMob adMob) throws Exception { ListAdUnitsResponse response; String nextPageToken = null; do { // Create and execute the ad units list request. response = adMob .accounts() .adUnits() .list(ACCOUNT_NAME) // ACCOUNT_NAME needs to be defined elsewhere .setPageSize(PAGE_SIZE) .setPageToken(nextPageToken) .execute(); // Display ad units. // The actual display logic for ad units is not provided in this snippet. // Example: iterate through response.getAdUnits() and print details. // Update the next page token. nextPageToken = response.getNextPageToken(); } while (nextPageToken != null); } ``` -------------------------------- ### Get AdMob Account Information with Python Source: https://developers.google.com/admob/api/v1/reporting This Python function retrieves and prints details of an AdMob account, such as its name, publisher ID, currency code, and reporting time zone. It requires an AdMob service object and the publisher ID as input. Ensure the publisher ID is correctly formatted. ```Python # Set the '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. PUBLISHER_ID = 'pub-XXXXXXXXXXXXXXXX' def get_account(service, publisher_id): """Gets and prints an AdMob account. Args: service: An AdMob Service Object. publisher_id: An ID that identifies the publisher. """ # Execute the request. response = service.accounts().get( name='accounts/{}'.format(publisher_id)).execute() # Print the response. print('Name: ' + response['name']) print('Publisher ID: ' + response['publisherId']) print('Currency code: ' + response['currencyCode']) print('Reporting time zone: ' + response['reportingTimeZone']) ``` -------------------------------- ### Authenticate User and Create AdMob Service Object (Python) Source: https://developers.google.com/admob/api/v1/reporting_hl=he Authenticates a user and creates a Google API Service Object for AdMob. It handles token storage and retrieval using pickle, and initiates the OAuth 2.0 flow if no valid tokens are found. Dependencies include os, pickle, googleapiclient.discovery, google_auth_oauthlib.flow, and google.auth.transport.requests. ```python import os import pickle import hashlib import socket import sys from googleapiclient.discovery import build from google_auth_oauthlib.flow import Flow from google.auth.transport.requests import Request API_NAME = 'admob' API_VERSION = 'v1' API_SCOPE = 'https://www.googleapis.com/auth/admob.readonly' TOKEN_FILE = 'token.pickle' PORT = 8080 REDIRECT_URI = 'http://localhost:8080/' def authenticate( api_name=API_NAME, api_version=API_VERSION, api_scopes=[API_SCOPE], ): """Authenticates a user and creates a Google API Service Object. Args: api_name: Google API name as shown in the API discovery doc. Defaults to the AdMob API. api_version: Google API version as shown in the API discovery doc. Defaults to v1. api_scopes: scope(s) to authenticate with oauth2 flow to access the APIs. Defaults to https://www.googleapis.com/auth/admob.readonly. Returns: A Google API Service Object that is authenticated with the user using either a client_secrets file or previously stored access and refresh tokens. By default, returns the AdMob API service object. """ # The TOKEN_FILE stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(TOKEN_FILE): with open(TOKEN_FILE, 'rb') as token: credentials = pickle.load(token) if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) # If there are no valid stored credentials, authenticate using the # client_secrets file. else: client_secrets = load_user_credentials() flow = Flow.from_client_secrets_file(client_secrets, scopes=api_scopes) flow.redirect_uri = REDIRECT_URI # Create an anti-forgery state token as described here: # https://developers.google.com/identity/protocols/OpenIDConnect#createxsrftoken passthrough_val = hashlib.sha256(os.urandom(1024)).hexdigest() # Redirect the user to auth_url on your platform. authorization_url, state = flow.authorization_url( access_type="offline", state=passthrough_val, included_granted_scopes="true") # Prints the authorization URL so you can paste into your browser. In a # typical web application you would redirect the user to this URL, and they # would be redirected back to "redirect_url" provided earlier after # granting permission. print("Paste this URL into your browser: ") print(authorization_url) print(f"\nWaiting for authorization and callback to: {REDIRECT_URI}...") # Retrieves an authorization code by opening a socket to receive the # redirect request and parsing the query parameters set in the URL. code = _get_authorization_code(passthrough_val) # Pass the code back into the OAuth module to get a refresh token. flow.fetch_token(code=code) refresh_token = flow.credentials.refresh_token credentials = flow.credentials print(f"\nYour refresh token is: {refresh_token}\n") # Save the credentials for the next run. with open(TOKEN_FILE, "wb") as token: pickle.dump(credentials, token) # Build the Google API service stub. service = build(api_name, api_version, credentials=credentials) return service def _get_authorization_code(passthrough_val): """Opens a socket to handle a single HTTP request containing auth tokens. Args: passthrough_val: an anti-forgery token used to verify the request received by the socket. Returns: a str access token from the Google Auth service. """ # Open a socket at localhost:PORT and listen for a request sock = socket.socket() sock.bind(("localhost", PORT)) sock.listen(1) connection, address = sock.accept() data = connection.recv(1024) # Parse the raw request to retrieve the URL query parameters. params = _parse_raw_query_params(data) try: if not params.get("code"): # If no code is present in the query params then there will be an # error message with more details. error = params.get("error") message = f"Failed to retrieve authorization code. Error: {error}" raise ValueError(message) elif params.get("state") != passthrough_val: message = "State token does not match the expected state." raise ValueError(message) else: message = "Authorization code was successfully retrieved." except ValueError as error: print(error) sys.exit(1) finally: response = ("HTTP/1.1 200 OK\n" "Content-Type: text/html\n\n" f"{message}" "

Please check the console output.

\n") connection.sendall(response.encode()) connection.close() return params.get("code") def _parse_raw_query_params(data): """Parses a raw HTTP request to extract its query params as a dict. Note that this logic is likely irrelevant if you're building OAuth logic into a complete web application, where response parsing is handled by a framework. Args: data: raw request data as bytes. Returns: a dict of query parameter key value pairs. """ # Decode the request into a utf-8 encoded string decoded = data.decode("utf-8") # Further parsing would be needed here to extract query parameters from the decoded string. # For example, you might split the string by '\r\n' to get the request line and headers, # and then parse the request line to find the URL, and then parse the URL query string. # This is a simplified placeholder. return {} # Placeholder for load_user_credentials function, which should handle def load_user_credentials(): # logic to load client_secrets.json or similar. # This is a placeholder and needs to be implemented based on actual credential management. print("Attempting to load user credentials...") # In a real application, this would return the path to your client_secrets.json file # or handle other credential loading mechanisms. return 'client_secrets.json' # Example usage (assuming client_secrets.json exists and PORT is available): # if __name__ == '__main__': # admob_service = authenticate() # print("AdMob API service object created successfully.") # # Now you can use admob_service to make API calls ``` -------------------------------- ### Generate AdMob Mediation Report (Java) Source: https://developers.google.com/admob/api/v1/reporting This code example shows how to generate a mediation report from AdMob. It requires an account name and a mediation report request object. The generated report is parsed and each record is printed. The report configuration includes date range, time zone, metrics, dimensions, sorting conditions, and dimension filters. ```java public static void runExample( AdMob adMob, String accountName, GenerateMediationReportRequest request) throws Exception { // Get mediation report. InputStream response = adMob .accounts() .mediationReport() .generate(accountName, request) .executeAsInputStream(); List result = Arrays.asList( new JsonObjectParser(Utils.getDefaultJsonFactory()) .parseAndClose( response, StandardCharsets.UTF_8, GenerateMediationReportResponse[].class)); // Print each record in the response stream. for (GenerateMediationReportResponse record : result) { System.out.printf("%s%n", record); } } public static GenerateMediationReportRequest getMediationReportRequest() { /* 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. */ 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 metrics = ImmutableList.of("CLICKS", "ESTIMATED_EARNINGS"); // Specify dimensions. ImmutableList dimensions = ImmutableList.of("APP", "AD_SOURCE", "COUNTRY"); // Specify sorting conditions. List sortConditions = new ArrayList(); sortConditions.add( new MediationReportSpecSortCondition().setOrder("ASCENDING").setMetric("CLICKS")); // Specify dimension filters. ImmutableList countryList = ImmutableList.of("CA", "US"); // TODO: Add the country filter to the report spec once it's supported. return null; } ``` -------------------------------- ### Authentication using oauth2l Source: https://developers.google.com/admob/api/v1/reporting This section outlines how to obtain authorization credentials using the oauth2l command-line tool. This is the first step before making any authenticated API calls. ```APIDOC ## Authentication ### Description Load client secrets and generate authorization credentials using `oauth2l`. This process involves an initial browser-based authorization flow. ### Method `oauth2l` command-line tool ### Endpoint `https://www.googleapis.com/auth/admob.readonly` ### Parameters #### Path Parameters - **path_to_credentials_json** (string) - Required - Path to your downloaded `credentials.json` file. ### Request Example ```bash oauth2l header --json path_to_credentials_json \ https://www.googleapis.com/auth/admob.readonly ``` ### Response Outputs authorization headers for subsequent API requests. ```