httr2
httr2 copied to clipboard
Discussion on expanding `httr2::oauth_client()`
This isn't really an issue, but really a discussion to collect thoughts on how I'm currently defining and using an OAuth2 client object for an API wrapper package, and whether it might form the basis of a new article.
I originally had the code of my client package using particular settings in terms of how it interfaced with the API baked in (hardcoded) to a lot of the functions. After reading in the Wrapping APIs vignette "you should always provide some way for the user to provide their own app", I thought about how I might separate out this logic to make it easier for a developer/user to change.
I've ended up creating a function which wraps httr2::oauth_client() but also adorns the object with additional client settings in terms of how it interfaces with the API.
my_client <- function(client_name = "My API client",
client_id = "44es4rere",
client_secret = httr2::obfuscated("fgesg5r4ste"),
store_token_on_disk = TRUE,
host = "http://sitename",
user_agent = "My API client ([email protected])",
req_rate = 1/3,
max_tries = 2){
cl <- httr2::oauth_client(id = client_id,
token_url = paste(host, "oauth2", "token", sep = "/"),
secret = client_secret,
auth = "header",
name = client_name)
cl$auth_url = paste(host, "oauth2", "authorize", sep = "/")
cl$store_token_on_disk <- store_token_on_disk
cl$host <- host
cl$user_agent <- user_agent
cl$req_rate <- req_rate
cl$max_tries <- max_tries
cl
}
All of my top level function then take in a client object with my_client() being the default.
Obviously you could customise this based on which httr2 features you've chosen to use; I've not chosen to use an explicit backoff for example. This obviates the need for me to have lots of these parameters floating around as function arguments and I can just store them in one object which characterises the client's interface to the API. I like it because everything is defined in one place.
My ultimate question is whether this is a sensible way of doing things and if anyone has done something similar? If it is of use, I wonder if it is something to write about in a article/vignette?
This has some overlap with how the gargle package and downstream packages work (googledrive, googlesheets4, bigrquery, gmailr, etc.). At the moment, all of that is still using httr, not httr2, so that implies a pretty different design.
But you might have a look at https://gargle.r-lib.org/articles/gargle-auth-in-client-package.html. The part that overlaps with what you describe above is how gargle and related packages implement helpers for generating and enacting requests.
I see a lot of similar thinking. I've since generalised the above function into 2 functions; one to create a client (basically the function above without many of the argument defaults) and another defining my specific client, which calls the client creation function. Then if the client is NULL it will use this specific client object.