liveBook · Manning

Environment variable

As explained in Rust Web Development

An environment variable is a named value supplied by a process's environment that programs can read to configure behavior.

An environment variable is a named value a program reads from its environment to configure behavior. For a web service, variables can replace hardcoded ports, host addresses, database settings, and keys, allowing a hosting provider to supply deployment-specific values. section 10.0 section 10.1.3

For local development, a root-level .env file can hold key-value pairs. Add the dotenv crate and call dotenv::dotenv().ok() at server startup to load them into the environment. Add .env to .gitignore so secrets in the file are not committed to the repository. section 10.1.3 section 11.1.2

Listing 10.7 The content of the .env file in the root folder of the project
BAD_WORDS_API_KEY=API_KEY_HIDDEN_FOR_THE_BOOK
PASETO_KEY="RANDOM WORDS WINTER MACINTOSH PC"
PORT=8080

This .env file supplies a port, an API key, and a PASETO key for local configuration. section 10.1.3

Read values in Rust with std::env::var. Check required keys before starting the server so a missing value fails early. Code that later unwraps a value depends on that startup check; for example, the profanity client reads BAD_WORDS_API_KEY and sends it in an API request header. section 10.1.3

Listing 10.11 Using the API key from the .env file in the check_profanity function
use std::env;
 
...
 
#[instrument]
pub async fn check_profanity(
    content: String
) -> Result<String, handle_errors::Error> {
    // We are already checking if the ENV VARIABLE is set inside main.rs, 
    // so safe to unwrap here
    let api_key = env::var("BAD_WORDS_API_KEY").unwrap();
 
    let retry_policy = 
        ExponentialBackoff::builder().build_with_max_retries(3);
    let client = ClientBuilder::new(reqwest::Client::new())
        .with(RetryTransientMiddleware::new_with_policy(retry_policy))
        .build();
 
("https://api.apilayer.com
            /bad_words?censor_character={censor_character}"
        )
        .header("apikey", api_key)
        .body(content)
        .send()
        .await
        .map_err(handle_errors::Error::MiddlewareReqwestAPIError)?;
 
    ...
}

The profanity client reads the checked API key and attaches it to the outgoing request. section 10.1.3

Environment variables can also change behavior during testing. An API URL variable lets the profanity client target a mock server instead of the external host. Logging levels can likewise be selected through environment variables to reduce unwanted output. section 11.1.3 section 6.1

Tests that set environment variables can affect other tests running in parallel. Move dotenv initialization out of Config::new and into startup so constructing the configuration does not load the file. One test can then check the missing-key case before setting variables and checking the resulting configuration; another option is to run tests with cargo test -- --test-threads=1. section 11.1.2

Listing 11.7 Combining the two config tests so the environment variables don’t interfere
...
    #[test]
    fn unset_and_set_api_key() {
        // ENV VARIABLES ARE NOT SET
        let result = std::panic::catch_unwind(|| Config::new());
        assert!(result.is_err());
 
        // NOW WE SET THEM
        set_env();
 
        let expected = Config {
            log_level: "warn".to_string(),
            port: 8080,
            db_user: "user".to_string(),
            db_password: "pass".to_string(),
            db_host: "localhost".to_string(),
            db_port: 5432,
            db_name: "rustwebdev".to_string(),
        };
 
        let config = Config::new().unwrap();
 
        assert_eq!(config, expected);
    }
}

The combined test checks the missing-key case first, then sets variables and compares the constructed configuration. section 11.1.2

How Rust Web Development covers it

How deep it goes
Walks through dotenv loading, variable lookup, startup checks, and test interference, without treating environment variables as an exhaustive reference.
Examples
Uses a port, PASETO key, API key, database settings, and configurable API URL in a Rust web service.
What you can do after
Apply it via dotenv and Rust's std::env to load and check web-service settings and test configuration behavior.
How it connects
Connects deployment configuration to secret management, logging, unit testing, and mock servers.

Also explained in

Compare how 21 books explain environment variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust Web Development. The section links point to the parts of the book it draws on.