Don't put your auth tokens in your R source code

I’ve been working with the great open data source which is BLS. You can get some of the data with the v1 API, but to use the v2 API you need to have a token. That simply takes a registration and a validation. Cheers to BLS. And cheers to Mikeasilva

So, now you have your API token and you want to go grab some data into some R and cook it up. So you might do something like:

install_github("mikeasilva/blsAPI")
payload <- list('seriesid'=c('LAUCN040010000000005','LAUCN040010000000006'),
                'startyear'='2010',
                'endyear'='2012',
                'catalog'='true',
                'calculations'='true',
                'annualaverage'='true',
                'registrationKey'= 'MYVERYOWNTOKENREGISTEREDTOME')
response json

Sadly, when you check your code into github, or share it with someone else, they have your API token. A better way exists, padawan. Go to your home dir


> normalizePath("~/")

in the R console will tell you if you don't know. So will a simple
cd

in a shell, but if you know what a shell is you knew that already :). In your home dir, edit a new file called .Renviron, unless it already exists, which questions why you are reading this post. In .Renviron, you can enter key-values per line:


BLS_API_TOKEN=11111111122222222333333333
GITHUB_TOKEN=11111111133333333322222222
BIGDATAUSERNAME=BIGDADDY
BIGDATAPASSWD=ROCKS
KEY=VALUE

and, beautifully, you can grab any and all of these values in your R code with the following:


myValueOfInterest <- Sys.getenv(KEY)
typeof(MyValueOfInterest)
[1] "character"

so you can easily pass it as a parameter to those connections. All much better than embedding it directly into the source. N.B.: If you happened to include your home dir as part of your project dir, don't commit the .Renviron. Also, go change your project directory to something more sensible like a child dir. While you're at it, look at some of the other methods available via Sys, e.g.:


Sys.setenv()
Sys.unsetenv()

Now your interaction with the v2 API is more like:


payload <- list('seriesid'=c('LAUCN040010000000005','LAUCN040010000000006'),
                'startyear'='2010',
                'endyear'='2012',
                'catalog'='true',
                'calculations'='true',
                'annualaverage'='true',
                'registrationKey'= BLS_API_TOKEN)
response <- blsAPI(payload)
json <- fromJSON(response)
response json 
twitter
twitter

Leave a Reply

Your email address will not be published. Required fields are marked *