Skip to content

Instantly share code, notes, and snippets.

@MarkEdmondson1234
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkEdmondson1234/f06ded1bc2a01233b8fb to your computer and use it in GitHub Desktop.
Save MarkEdmondson1234/f06ded1bc2a01233b8fb to your computer and use it in GitHub Desktop.
Demo using googleAuthR to create a Google API package
library(googleAuthR)
## change the native googleAuthR scopes to the one needed.
options("googleAuthR.scopes.selected" =
c("https://www.googleapis.com/auth/urlshortener"))
#' Shortens a url using goo.gl
#'
#' @param url URl to shorten with goo.gl
#'
#' @return a string of the short URL
shorten_url <- function(url){
body = list(
longUrl = url
)
f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
"POST",
data_parse_function = function(x) x$id)
f(the_body = body)
}
#' Expands a url that has used goo.gl
#'
#' @param shortUrl Url that was shortened with goo.gl
#'
#' @return a string of the expanded URL
expand_url <- function(shortUrl){
f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
"GET",
pars_args = list(shortUrl = "shortUrl"),
data_parse_function = function(x) x)
f(pars_arguments = list(shortUrl = shortUrl))
}
#' Get analyitcs of a url that has used goo.gl
#'
#' @param shortUrl Url that was shortened with goo.gl
#' @param timespan The time period for the analytics data
#'
#' @return a dataframe of the goo.gl Url analytics
analytics_url <- function(shortUrl,
timespan = c("allTime", "month", "week","day","twoHours")){
timespan <- match.arg(timespan)
f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
"GET",
pars_args = list(shortUrl = "shortUrl",
projection = "FULL"),
data_parse_function = function(x) {
a <- x$analytics
return(a[timespan][[1]])
})
f(pars_arguments = list(shortUrl = shortUrl))
}
#' Get the history of the authenticated user
#'
#' @return a dataframe of the goo.gl user's history
user_history <- function(){
f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url/history",
"GET",
data_parse_function = function(x) x$items)
f()
}
## To use the above functions:
library(googleAuthR)
# go through authentication flow
gar_auth()
s <- shorten_url("http://markedmondson.me")
s
expand_url(s)
analytics_url(s, timespan = "month")
user_history()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment