dietrichson / ProPublicaR

R Functions to Interact with the ProPublica APIs
GNU General Public License v2.0
12 stars 4 forks source link

Trouble getting API key from the config.yaml (with suggested fix) #10

Closed jsowder closed 4 years ago

jsowder commented 4 years ago

I attempted to put my API key into my config.yaml so I wouldn't have to call it with every function, but I could not get the pp_query function to recognize it.

Currently the command to retrieve the API key from config.yml is:

myAPI_Key <- config::get('ProPublica')[[API]]

I set my key in config.yml using:

default:
 ProPublica:
   API: mykey123456789

But because R is calling [[API]] with API as an object rather than a string pp_query wouldn't recognize it. I can retrieve it if I change the command to:

config::get('ProPublica')[['API']]

Is this the best fix? Or am I missing a way to set the API object?

Thanks! Happy to fix it in pp_query if needed.

jsowder commented 4 years ago

Came to understand what the original method was doing! However, wrote a new method to allow for generic environment variables to be used instead.

Here's the retrieve_key code for quick checking:

retrieve_key <- function(API = c('congress', 'campaign-finance')){
  if (!is.null(config::get('ProPublica')[[API]])) {
    myAPI_Key <- config::get('ProPublica')[[API]]
  } else if (API == 'congress' && !is.null(.GlobalEnv$key_congress)) {
    myAPI_Key <- .GlobalEnv$key_congress
  } else if (API == 'campaign-finance' && !is.null(.GlobalEnv$key_campaign_finance)) {
    myAPI_Key <- .GlobalEnv$key_campaign_finance
  } else {
    stop(
      "
      API key not found or is missing. 

      1. Set a variable 'key_congress' to your API 
      key for the Congress API, and/or a variable 
      'key_campaign_finance' to your API key for the 
      Campaign Finance API. For example:

      key_congress <- 'my_key_123' 
      key_campaign_finance <- 'my_other_key_123' 

      2. Alternatively, set the same two variables 
      in a file called config.yml (in your working
      directory or higher). These variables should
      be under 'ProPublica' and be named 'congress'
      and 'campaign-finance' respectively.

      3. Finally, you may just include the key as
      an argument to each of your functions.
      "
    )
  }
  return(myAPI_Key)
}