> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Understanding Environment Variables in Python Projects

> Learn what environment variables are, why they matter for keeping secrets safe, and how to read and set them from Python using the os module.

Environment variables are named values stored at the operating system level, completely outside your application code. When your Python program runs, it can ask the OS for those values at any time — but the values themselves never appear in your source files. This separation is what makes them the right place to store anything that's sensitive (like API keys), machine-specific (like a database URL that differs on each developer's laptop), or likely to change between environments (like whether debug mode is on or off).

## The problem they solve

```python theme={null}
# BAD — never hardcode sensitive data like this!
api_key = "sk-1234567890abcdef"   # Anyone reading this code can see it
database = "production_database"  # Can't change without editing the code
```

This pattern creates three problems:

* Secrets are visible in your code and Git history
* You can't safely share your code with others
* Different machines need different settings but require code changes

## How environment variables work

Environment variables live in your operating system, not in your code:

```python theme={null}
import os

# Read from the environment — nothing sensitive ever appears here
api_key  = os.environ.get("API_KEY")
database = os.environ.get("DATABASE_NAME", "default.db")

print(f"Using database: {database}")
```

## Setting them in the terminal

You can set environment variables temporarily from the terminal:

<CodeGroup>
  ```bash macOS/Linux theme={null}
  export API_KEY=sk-1234567890abcdef
  python app.py
  ```

  ```powershell Windows theme={null}
  set API_KEY=sk-1234567890abcdef
  python app.py
  ```
</CodeGroup>

The variable is available while that terminal session is open. Close the terminal and it's gone — which is why `.env` files (covered on the next page) are a better approach for persistent configuration.

## Reading environment variables in Python

```python theme={null}
import os

# Method 1: Get with a fallback default
api_key = os.environ.get("API_KEY", "demo-key")

# Method 2: Check first, then use
if "API_KEY" in os.environ:
    api_key = os.environ["API_KEY"]
else:
    print("No API key found — using demo mode")

# Method 3: Crash loudly if the variable is missing
api_key = os.environ["API_KEY"]  # Raises KeyError if not set
```

<Tip>
  Method 1 (`.get()` with a default) is the most common in practice. Method 3 is useful when a missing variable should be treated as an unrecoverable error, such as when starting a server without its required credentials.
</Tip>

## Common uses

* **API keys** — `OPENAI_API_KEY`, `GITHUB_TOKEN`, `STRIPE_SECRET_KEY`
* **Database URLs** — `DATABASE_URL`, `REDIS_URL`
* **App settings** — `DEBUG=True`, `PORT=8000`, `LOG_LEVEL=INFO`
* **File paths** — `LOG_DIR`, `UPLOAD_FOLDER`

## Important rules

* Environment variables are **always strings** — if you need a number or boolean, convert them explicitly (`int(os.environ.get("PORT", "8000"))`)
* Names are **UPPERCASE** by convention
* Values are **machine-specific** — your `DATABASE_URL` will be different from a teammate's
* They **don't persist** between terminal sessions unless you set them in a shell profile or use a `.env` file

## What's next?

Setting variables by hand every session is tedious. `.env` files give you a much cleaner workflow.

<Card title="Using .env files" icon="file-shield" href="/tools/environment/dotenv">
  The easier way to manage environment variables
</Card>
