A wrapper around tidycensus::census_api_key() that checks for a Census API key using a cascading lookup: (1) the explicit key argument, (2) the CENSUS_API_KEY environment variable, (3) an interactive prompt. If no key can be resolved in a non-interactive session, an informative error is raised.

dep_set_api_key(key = NULL, install = FALSE, overwrite = FALSE)

Arguments

key

A character scalar; a Census API key. If NULL (default), the function checks the CENSUS_API_KEY environment variable and, if that is also unset, prompts interactively.

install

A logical scalar; if TRUE, the key is written to .Renviron for use in future sessions (via tidycensus::census_api_key(install = TRUE)). Defaults to FALSE, which sets the key for the current session only.

overwrite

A logical scalar; if TRUE and install = TRUE, an existing key in .Renviron will be overwritten. Defaults to FALSE.

Value

The Census API key (invisibly), as returned by tidycensus::census_api_key().

Details

The lookup order is:

  1. If key is provided (non-NULL), it is used directly.

  2. If key is NULL, the function checks Sys.getenv("CENSUS_API_KEY"). If that is set (non-empty), it is used.

  3. If neither is available and the session is interactive, the user is prompted to enter their key with setup instructions.

  4. If the session is non-interactive and no key is found, an error is raised with instructions for setting the environment variable.

Examples

if (FALSE) { # \dontrun{
  # Use an explicit key (session only)
  dep_set_api_key(key = "your_key_here")

  # Install key to .Renviron for future sessions
  dep_set_api_key(key = "your_key_here", install = TRUE)

  # Rely on CENSUS_API_KEY env var or interactive prompt
  dep_set_api_key()
} # }