|
#' Interface with the Stattleship API |
|
#' |
|
#' A simple, generic function to query data from the API |
|
#' |
|
#' @param token character. A valid token for the API |
|
#' @param sport character. The sport, such as hockey, basketball, football |
|
#' @param league character. NHL, NBA, etc. |
|
#' @param ep character. The endpoint |
|
#' @param query A list that defines the query parameters |
|
#' @param version The API version. Current version is 1. |
|
#' @param page numeric. The page number to request |
|
#' @param verbose logical. For debugging, returns response and parsed response. |
|
#' |
|
#' @examples |
|
#' \dontrun{ |
|
#' TOKEN = "aklsjdlfkajsfdas" |
|
#' results = queryAPI(TOKEN, |
|
#' sport="hockey", |
|
#' query=list(player_id="akjasdf") |
|
#' version = 1, |
|
#' ep = "stats", |
|
#' verbose = F) |
|
#' |
|
#' @export |
|
queryAPI = function(token, |
|
sport="hockey", |
|
league = "nhl", |
|
ep="stats", |
|
query=list(), |
|
version=1, |
|
walk=F, |
|
page=NA, |
|
verbose=F) { |
|
|
|
## TODO: walk the results if > 20 entries |
|
## TODO: test to validate data types |
|
## TODO: best practices on walking the data? Have # entries paramter? |
|
|
|
## packages : doesnt feel like this is the right way to do it |
|
library(httr) |
|
|
|
## build the URL and the endpoint |
|
URL = sprintf("https://www.stattleship.com/%s/%s/%s", sport, league, ep) |
|
|
|
## the accept parameters. Is there a better way to do this? |
|
ACCEPT = sprintf("application/vnd.stattleship.com; version=%d", version) |
|
|
|
## if page is supplied, add it to the list |
|
if (!is.na(page) & is.numeric(page) & page >= 1) { |
|
query = c(query, page=page) |
|
} |
|
|
|
## test the body to see if it is a list and has values |
|
## if not, just return an empty list |
|
## todo: test to ensure that query is a list if !is.na |
|
## get the request from the API |
|
resp = GET(URL, |
|
add_headers(Authorization =TOKEN, |
|
Accept = ACCEPT, |
|
`Content-Type`="application/json"), |
|
query=query) |
|
|
|
|
|
## convert response to text first, do not use baseline httr::content default |
|
api_response = content(resp, as="text") |
|
|
|
## use jsonlite::fromJSON |
|
api_response = jsonlite::fromJSON(api_response) |
|
|
|
## if verbose = T, return a list that includes the parsed results |
|
## and the original request |
|
if (verbose) { |
|
api_response = list(response = resp, |
|
api_json = api_response) |
|
} |
|
|
|
## return the data |
|
return(api_response) |
|
} |