R/yahoo_api.R

Defines functions yahoo_api print.yahoo_api authenticate app_keys

Documented in yahoo_api

#' Yahoo API Interaction
#'
#' @param path
#'
#' @return
#'
#' @import httr
#' @import httpuv
#' @import jsonlite
#'
#' @export
#'
#' @examples
#' yahoo_api(path)
yahoo_api <- function(path) {

  config <- authenticate()
  ua <- user_agent("http://github.com/TK2575/ff_data")

  base <- "https://fantasysports.yahooapis.com/fantasy/v2/"
  req_json <- "/?response=json"

  url <- paste0(base, path, req_json)

  resp <- GET(url = url, config = config, ua)
  if (http_type(resp) != "application/json") {
    stop("API did not return json", call. = F)
  }

  parsed <- fromJSON(content(resp, "text"),
                     simplifyVector = F)

  if (status_code(resp) != 200) {
    stop(
      sprintf(
        "Yahoo API request failed [%s]\n%s\n<%s>",
        status_code(resp),
        parsed$message,
        parsed$documentation_url
      ),
      call. = F
    )
  }

  structure(
    list(
      content = parsed,
      path = path,
      response = resp
    ),
    class = "yahoo_api"
  )

}

print.yahoo_api <- function(x, ...) {
  cat("<Yahoo ", x$path, ">\n", sep = "")
  str(x$content)
  invisible(x)
}

authenticate <- function() {
  keys <- app_keys()

  endpoint <- oauth_endpoint("get_request_token",
                             "request_auth",
                             "get_token",
                             base_url = "https://api.login.yahoo.com/oauth2")

  app <- oauth_app("yahoo",
                   key = keys[1],
                   secret = keys[2],
                   redirect_uri = "oob")

  token <- oauth2.0_token(endpoint,
                          app,
                          use_oob = T,
                          as_header = T,
                          use_basic_auth = T,
                          cache = T)

  config(token = token)
}

app_keys <- function() {
  key <- Sys.getenv('YAHOO_KEY')
  secret <- Sys.getenv('YAHOO_SECRET')

  if (identical(key, "") || identical(secret, "")) {
    stop("Please set env var YAHOO_KEY to your Yahoo app key, and YAHOO_SECRET to your Yahoo app secret",
         call. = F)
  }

  c(key,secret)
}
TK2575/fantasyFootballData documentation built on May 17, 2019, 10:37 a.m.