Search code examples
rgoogleway

Permanently save googleway API key


Is there any way to permanently save the API key to my R profile or environment so that I don't have use set_key() every session? I don't like to save keys in my code since it is on github.


Solution

  • You could put it in your First function, which is located in your Rprofile.site file.

    I'm not sure what platform you are on, but this should work

    rfile <- list.files(path = Sys.getenv("R_HOME"), recursive = TRUE, 
                        full.names = TRUE, pattern = "Rprofile.site")
    file.edit(rfile)
    

    Rprofile.site should now be open in your editor. NOTE: you may need to adjust file permissions of the file on your system in order to write to it(save it)

    Add this to the .First

    # Things you might want to change
    # options(papersize="a4")
    # options(editor="notepad")
    # options(pager="internal")
    # set the default help type
    # options(help_type="text")
    .First <- function(){
      # Your string api key
      google_api_key <- "12345"
      # Use assign to explicitly set the environment in which to populate the key
      assign("my_google_key", google_api_key, envir = .GlobalEnv)
    }
    

    Save the file and restart R

    enter image description here

    Edit

    If your api key is an Token object, such as oauth, simply save to a file and read in and assign to the google_api_key value. Such as:

    .First <- function(){
      # Your oauth api key read in from file
      google_api_key <- readRDS("~/.hide_google_token.rds")
      # Use assign to explicitly set the environment in which to populate the key
      assign("google_oauth_token", google_api_key, envir = .GlobalEnv)
    }
    

    enter image description here