PURPOSE: Use httr2 + github + oauth 2.0

REF : GITHUB and GIST https://httr2.r-lib.org/articles/httr2.html

knitr::opts_chunk$set(echo = TRUE,
                      comment = "      ##",
                      error = TRUE,
                      collapse = TRUE)
library(httr2)

show HEADERS

##  replace httr2:: function with wrapper.  Makes default to NOT redact.

req_dry_run  <- function(..., redact_headers=F) {
    httr2::req_dry_run(..., redact_headers=redact_headers)
}

Prefix file name with _ (underscore) and git will not include it

(Example)

writeLines(text = "FOO", con = "_secret_file") 
readLines("_secret_file")

read API codes from ~/.Renviron and save to local file that git ignores

## github token, for GIST only

HTTR2_GIST  <- Sys.getenv("HTTR2_GIST")
HTTR2_GIST
writeLines(text = paste0("HTTR2_GIST=", HTTR2_GIST), con= " _HTTR2_GIST")
token  <- HTTR2_GIST

Follow Vignette for OAUTH and GITHUB

Authenication

##  Github does not permit standalone oauth clients.
##  This is Hadley's client/  I can't recreate my own:  what is URL??


client <- oauth_client(
  id = "28acfec0674bb3da9f38",
  secret = obfuscated("J9iiGmyelHltyxqrHXW41ZZPZamyUNxSX1_uKnvPeinhhxET_7FfUs2X0LLKotXY2bpgOMoHRCo"),
  token_url = "https://github.com/login/oauth/access_token",
  name = "hadley-oauth-test"
)


client

##  Per Hadley, use flow:  auth_code

##  github window pops up to authorizee 
##  auth_url is endpoint to obtain user
token <- oauth_flow_auth_code(client, auth_url = "https://github.com/login/oauth/authorize")

#   token is list, token_type, access_token itself, scope
# in this case, has no scope!
token
str(token)

At this point, we have access token and we can make request (user info)

        To do so, we tell github we send the same token as a `bearer_token`
# First, he says do htis and it prints "jim"

request("https://api.github.com/user") %>% 
  req_auth_bearer_token(token$access_token) %>% 
  req_perform() %>% 
  resp_body_json() %>%
  .$name
# 

Easier way: let httr2 handled intermediate details (ie token)

# Then he says this is better, which prints stuff about me.
##  Again browser pops up, but authentication is done automatically.
request("https://api.github.com/user") %>% 
  req_oauth_auth_code(client, auth_url = "https://github.com/login/oauth/authorize") %>% 
  req_perform() 


##  adding this piece prints to conosole as list
# %>% 
# resp_body_json()


  ## find cached tokens?
rappdirs::user_cache_dir("httr2")
# [1] "/home/jim/.config/cache/httr2"

dir(rappdirs::user_cache_dir("httr2"), recursive = TRUE)
# character(0)


jimrothstein/yt_api documentation built on Nov. 5, 2022, 8:05 p.m.