Search code examples
rapiadmob

Connecting to Admob with r


Is there smooth solution to query data from Google Admob API into R environment? (for e.g. similar to googleAnalyticsR package).


Solution

  • So if anyone ever is looking for an answer the solution that i worked out is to use library(httr) and library(jsonlite) which are general packages for managing API's

    First set up your google app for admob and generate oauth credentials, store them in as described below and authorize token.

    Obtain Token:

    options(admob.client_id = client.id)
    options(admob.client_secret = key.secret)
    
    
    # GETTING OAUTH TOKEN
    token = oauth2.0_token(endpoint = oauth_endpoints("google"), # 'google is standard
                   app = oauth_app(appname = "google",
                     key = getOption('admob.client_id'),
                     secret = getOption("admob.client_secret")
                   ),
                   scope = r"{https://www.googleapis.com/auth/admob.report}",
                   use_oob = TRUE,
                   cache = TRUE)
    

    You can generate your body request in within avaible google documentation in here:
    https://developers.google.com/admob/api/v1/reference/rest/v1/accounts.networkReport/generate

    I'am passing mine as.list:

    `json body` = toJSON(list(`reportSpec` = list(
      `dateRange` = list(
        `startDate` = list(
          `year` = 2021,
          `month` = 10,
          `day` = 20),
        `endDate` = list(
          `year` = 2021,
          `month` = 10,
          `day` = 22
        )),
      `dimensions` = list("DATE"),
      `metrics` = list("IMPRESSIONS")
    )), auto_unbox = TRUE)
    

    Query your request:

    test = POST(url = 'https://admob.googleapis.com/v1/accounts/YOURPUBIDGOESINHERE/networkReport:generate',
                add_headers(`authorization` = paste("Bearer",
                                                    token$credentials$access_token)),
                add_headers(`content-type` = "application/json"),
                body = `json body`
                )
    

    Finalize with some data cleansing and you are done.

    jsonText = content(test, as = 'text')
    df = fromJSON(jsonText, flatten = T)
    df = na.omit(df[c('row.metricValues.IMPRESSIONS.integerValue',
                      'row.dimensionValues.DATE.value')]) # select only needed columns
    row.names(df) = NULL # reindex rows
    df