I am in the process of writing an R package that is an API wrapper with a few extras. The API itself is provided by a 3rd party and sadly lacks (public) documentation. The API authorisation process involves two steps:
- Call to the login endpoint with user/password credentials, which returns a token.
- Authorisation to endpoints containing user content (e.g.
/user/data
) uses this token.
A minimal example looks like this:
# Login request
result <-
httr2::request("https://api.example.com/user/login") |>
httr2::req_headers("Accept" = "application/json") |>
httr2::req_body_json(list(email = "[email protected]", password = "XXX")) |>
httr2::req_perform()
token <- httr2::resp_body_json(result)$token
# Content request
result_2 <-
httr2::request("https://api.example.com/user/data") |>
httr2::req_method("POST") %>%
httr2::req_auth_bearer_token(token) %>%
httr2::req_perform()
The token in token
has an unknown TTL (but a long time and needs to remain secret) and can be used for more than one request. Users of my package will need to use their own credentials.
I’m wondering what’s the best way to handle these credentials or whether I shouldn’t bother at all and leave that option to the user. Should I store the token in some background variable, read it from the environment, or what would you expect? What are the best practices in that regard? Maybe you can point me to some literature?
The simplest way I can imagine (with boiler plate code) is to expose the token to the user:
# Login
token <- mypackage::service_auth(user, password)
# Get Content
mypackage::service_get_content(token, coverage = "daily", ...)
1