Creating your own API should be a matter of consulting the Google API documentation, and filling in the required details.
gar_api_generator()
has these components:
baseURI
- all APIs have a base for every API callhttp_header
- what type of request, most common are GET and POSTpath_args
- some APIs need you to alter the URL folder structure when calling, e.g. /account/{accountId}/
where accountId
is variable.pars_args
- other APIS require you to send URL parameters e.g. ?account={accountId}
where accountId
is variable.data_parse_function
- [optional] If the API call returns data, it will be available in $content
. You can create a parsing function that transforms it in to something you can work with (for instance, a dataframe)Example below for generating a function:
<- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
f "POST",
data_parse_function = function(x) x$id)
The function generated uses path_args
and pars_args
to create a template, but when the function is called you will want to pass dynamic data to them. This is done via the path_arguments
and pars_arguments
parameters.
path_args
and pars_args
and path_arguments
and pars_arguments
all accept named lists.
If a name in path_args
is present in path_arguments
, then it is substituted in. This way you can pass dynamic parameters to the constructed function. Likewise for pars_args
and pars_arguments
.
## Create a function that requires a path argument /accounts/{accountId}
<- gar_api_generator("https://www.googleapis.com/example",
f "POST",
path_args = list(accounts = "defaultAccountId")
data_parse_function = function(x) x$id)
## When using f(), pass the path_arguments function to it
## with the same name to modify "defaultAccountId":
<- f(path_arguments = list(accounts = "myAccountId")) result
A lot of Google APIs look for you to send data in the Body of the request. This is done after you construct the function. googleAuthR
uses httr
’s JSON parsing via jsonlite
to construct JSON from R lists.
Construct your list, then use jsonlite::toJSON
to check if its in the correct format as specified by the Google documentation. This is often the hardest part using the API.
To aid debugging use the options(googleAuthR.verbose = 0)
to see all the sent and recieved HTTP requests, and also write what was sent as JSON in the body is written to a file called request_debug.rds
in the working directory.
Example:
library(googleAuthR)
library(googleAnalyticsR)
options(googleAuthR.verbose = 0)
ga_auth()
<- google_analytics_4(1212121, date_range = c(Sys.Date() - 7, Sys.Date()), metrics = "sessions")
blah
Calling APIv4....
Single v4 batch
Token exists.
Valid local token: https://analyticsreporting.googleapis.com/v4/reports:batchGet/
Request: {"reportRequests":[{"viewId":"ga:121211","dateRanges":[{"startDate":"2017-01-06","endDate":"2017-01-13"}],"samplingLevel":"DEFAULT","metrics":[{"expression":"ga:sessions","alias":"sessions","formattingType":"METRIC_TYPE_UNSPECIFIED"}],"pageToken":"0","pageSize":1000,"includeEmptyRows":true}]}
Body JSON parsed to-> POST /v4/reports:batchGet/ HTTP/1.1
-> Host: analyticsreporting.googleapis.com
-> User-Agent: googleAuthR/0.4.0.9000 (gzip)
-> Accept: application/json, text/xml, application/xml, */*
-> Content-Type: application/json
-> Accept-Encoding: gzip
-> Authorization: Bearer ya29XXXXX_EhpEot1ZPNP28MUmSz5EyQ7lY3kgNCFEefYv-Zof3a1RSwezgMJ5llCO44TA9iHi51c
-> Content-Length: 295
->
>> {"reportRequests":[{"viewId":"ga:1212121","dateRanges":[{"startDate":"2017-01-06","endDate":"2017-01-13"}],"samplingLevel":"DEFAULT","metrics":[{"expression":"ga:sessions","alias":"sessions","formattingType":"METRIC_TYPE_UNSPECIFIED"}],"pageToken":"0","pageSize":1000,"includeEmptyRows":true}]}
<- HTTP/1.1 200 OK
<- Content-Type: application/json; charset=UTF-8
<- Vary: Origin
<- Vary: X-Origin
<- Vary: Referer
<- Content-Encoding: gzip
<- Date: Fri, 13 Jan 2017 10:45:38 GMT
<- Server: ESF
<- Cache-Control: private
<- X-XSS-Protection: 1; mode=block
<- X-Frame-Options: SAMEORIGIN
<- X-Content-Type-Options: nosniff
<- Alt-Svc: quic=":443"; ma=2592000; v="35,34"
<- Transfer-Encoding: chunked
<-
1] rows from a total of [1].
Downloaded [
> readRDS("request_debug.rds")
$url
1] "https://analyticsreporting.googleapis.com/v4/reports:batchGet/"
[
$request_type
1] "POST"
[
$body_json
"reportRequests":[{"viewId":"ga:1212121","dateRanges":[{"startDate":"2017-01-06","endDate":"2017-01-13"}],"samplingLevel":"DEFAULT","metrics":[{"expression":"ga:sessions","alias":"sessions","formattingType":"METRIC_TYPE_UNSPECIFIED"}],"pageToken":"0","pageSize":1000,"includeEmptyRows":true}]} {
Not all API calls return data, but if they do:
If you have no data_parse_function
then the function returns the whole request object. The content is available in $content
. You can then parse this yourself, or pass a function in to do it for you.
If you parse in a function into data_parse_function
, it works on the response’s $content
.
Example below of the differences between having a data parsing function and not:
## the body object that will be passed in
= list(
body longUrl = "http://www.google.com"
)
## no data parsing function
<- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
f "POST")
<- f(the_body = body)
no_parse
## parsed data, only taking request$content$id
<- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
f2 "POST",
data_parse_function = function(x) x$id)
<- f2(the_body = body)
parsed
## str(no_parse) has full details of API response.
## just looking at no_parse$content as this is what API returns
> str(no_parse$content)
3
List of $ kind : chr "urlshortener#url"
$ id : chr "http://goo.gl/ZwT9pG"
$ longUrl: chr "http://www.google.com/"
## compare to the above - equivalent to no_parse$content$id
> str(parsed)
"http://goo.gl/mCYw2i"
chr
The response is turned from JSON to a dataframe if possible, via jsonlite::fromJSON
From 0.4
is helper functions that use Google’s API Discovery service.
This is a meta-API which holds all the necessary details to build a supported Google API, which is all modern Google APIs. At the time of writing this is 152 libraries.
These libraries aren’t intended to be submitted to CRAN or used straight away, but should take away a lot of documentation and function building work so you can concentrate on tests, examples and helper functions for your users.
Get a list of the current APIs via gar_discovery_apis_list()
<- gar_discovery_apis_list() all_apis
To get details of a particular API, use its name and version in the gar_discovery_api()
function:
<- gar_discovery_api("urlshortener", "v1") a_api
You can then pass this list to gar_create_package()
along with a folder path to create all the files necessary for an R library. There are arguments to set it up with RStudio project files, do a CRAN CMD check
and upload it to Github.
<- gar_discovery_api("vision", "v1")
vision_api gar_create_package(vision_api,
"/Users/mark/dev/R/autoGoogleAPI/",
rstudio = FALSE,
github = FALSE)
A loop to build all the Google libraries is shown below, the results of which is available in this Github repo.
library(googleAuthR)
<- gar_discovery_apis_list()
api_df
<- mapply(gar_discovery_api, api_df$name, api_df$version)
api_json_list
## WARNING: this takes a couple of hours
<- lapply(api_json_list,
check_results
gar_create_package, directory = "/Users/mark/dev/R/autoGoogleAPI",
github = FALSE)
Below is an example building a link shortner R package using googleAuthR
. It was done referring to the documentation for Google URL shortener. Note the help docs specifies the steps outlined above. These are in general the steps for every Google API.
https://www.googleapis.com/urlshortener/v1/url
)POST
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
<- function(url){
shorten_url
= list(
body longUrl = url
)
<- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
f "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
<- function(shortUrl){
expand_url
<- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
f "GET",
pars_args = list(shortUrl = "shortUrl"),
data_parse_function = function(x) x)
f(pars_arguments = list(shortUrl = shortUrl))
}#' Get analytics 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
<- function(shortUrl,
analytics_url timespan = c("allTime", "month", "week","day","twoHours")){
<- match.arg(timespan)
timespan
<- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
f "GET",
pars_args = list(shortUrl = "shortUrl",
projection = "FULL"),
data_parse_function = function(x) {
<- x$analytics
a 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
<- function(){
user_history <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url/history",
f "GET",
data_parse_function = function(x) x$items)
f()
}
To use the above functions:
library(googleAuthR)
# go through authentication flow
gar_auth()
<- shorten_url("http://markedmondson.me")
s
sexpand_url(s)
analytics_url(s, timespan = "month")
user_history()
Another example is shown below to fetch your Google calendar entries. The below uses the API skeletons functions that are auto generated via the gar_discovery_api
functions.
Make sure the calendar API is activated for your Google Project at below URL: https://console.cloud.google.com/apis/api/calendar-json.googleapis.com/overview
#' Gets a list of events for calendarId
#'
#' @param calendarId The calendar to get. Default is primary for authenticated user
#' @return a big list of JSON
<- function(calendarId = "primary") {
events.list <- sprintf("https://www.googleapis.com/calendar/v3/calendars/%s/events",
url
calendarId)
<- googleAuthR::gar_api_generator(url, "GET",
f data_parse_function = function(x) x)
f()
}
To use your function:
library(googleAuthR)
## set scopes for calendar
options(googleAuthR.scopes.selected = "https://www.googleapis.com/auth/calendar.readonly",
googleAuthR.client_id = "XXXX", ## add your Google project client Id
googleAuthR.client_secret = "XXXX") ## add your Google project client secret
## authenticate with email that has access to the calendar
gar_auth()
## should kick you out to Google OAuth2 flow. Come back here when done....
## get default (primary) calendar list
<- events.list()
events
## events is raw JSON response,
## parse down to items by modifying the data_parse_function in events.list()
## or operating afterwards in code like below
$items$summary events