httr Two Common Authentication Methods

What I just learned that there can be a couple of authentication methods used in R API wrapper packages but the most common ones are API Key and OAuth 2.0.

API Key

API Key normally can be generated on a developer dashboard and can be regenerated later for security reason.

API Key can be saved as an environment variable in a .Renviron file and then we can use Sys.getenv() to get access to it, as shown here: https://github.com/maelle/goodpress/blob/main/R/utils-http.R.

keyring package is another common way to manage API Key: key_set() to create api key and key_get() to get access to the api key, as shown here: https://github.com/lockedata/hubspot/blob/master/R/hubspot_key.R.

Lastly, there are two different ways to include an api key in api calls: including it as part of the URL or adding it in the HTTP header.

For example, HubSpot requires that api key needs to be added in the url (https://developers.hubspot.com/docs/api/intro-to-auth), while Leadfeeder asks developers to include it in the HTTP header (https://docs.leadfeeder.com/api/#authentication).

OAuth 2.0

Take HubSpot for example. https://developers.hubspot.com/docs/api/oauth-quickstart-guide illustrates the steps in working with OAuth 2.0.

Accordingly, the steps in httr are:

  • Step 1: provide the app information with oauth_app()
oauth_app <- oauth_app(
  appname = app_name, 
  key = client_id, # from developer dashboard
  secret = client_secret # from developer dashboard
)
  • Step 2: build an endpoint with oauth_endpoint()
oauth_endpoint <- oauth_endpoint(
  authorize = authorize_url, # needs to be constructed first
  access = access_url # needs to be constructed first
)
  • Step 3: create a token with oauth2.0_token()
token <- oauth2.0_token(
  endpoint = oauth_endpoint,
  app = oauth_app
)
  • Step 4: save the token into a file and create an environment variable pointing to it

  • Step 5: use the token in every api call

Token can be accessed with token$credentials$access_token and should be added in HTTP headers with add_headers() or config().

  • Step 6: refresh token with token$refresh()

Here is an example that implements all the steps above for HubSpot OAuth 2.0: https://github.com/lockedata/hubspot/blob/master/R/hubspot_oauth.R.

Besides learning from the source code on github, I found the following articles very useful:

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
bwerpipes in baghdad
8 months ago

Bwer Pipes – Your Trusted Partner for Agricultural Irrigation in Iraq: Explore Bwer Pipes for reliable irrigation solutions tailored for Iraqi agriculture. From durable pipes to advanced sprinkler systems, we have everything you need to optimize your crop yields. Visit Bwer Pipes