How to Securely Manage Data Provider API Keys Within OpenBB
OpenBB automatically loads API keys from environment variables or a local JSON file, masking them with Pydantic's SecretStr to prevent accidental exposure while providing simple programmatic access.
Managing credentials for multiple financial data providers is a critical security concern when using the OpenBB Platform. The OpenBB-finance/OpenBB repository implements a centralized Credentials model that securely handles API keys from multiple sources without requiring hard-coded secrets in your analysis scripts. This architecture ensures that sensitive provider tokens remain protected while remaining accessible to the platform's data connectors.
Understanding OpenBB's Credentials Architecture
The OpenBB Platform uses a dynamic Pydantic model to handle authentication credentials across all data providers. This system prioritizes security by design, ensuring that raw API keys are never accidentally logged or displayed.
The Credentials Model and SecretStr
At the core of the system is the Credentials class defined in openbb_platform/core/openbb_core/app/model/credentials.py. This model dynamically generates fields based on registered data providers, typing each API key as SecretStr【source: Credentials model implementation】.
SecretStr is a Pydantic type that masks the underlying value during string conversion or JSON serialization. When you print a Credentials object, you see ********** instead of the actual key, preventing accidental exposure in notebooks or logs.
Three Secure Sources for API Keys
The CredentialsLoader.load method (lines 26-48) aggregates credentials from three distinct sources in order of precedence:
- User settings file (
~/.openbb_platform/user_settings.json) – A local JSON file storing persistent credentials【source: lines 26-33】 - Environment variables – Any variable ending with
API_KEY(e.g.,ALPHAVANTAGE_API_KEY)【source: lines 41-48】 - Provider registry – Each provider declares required credential names via
ProviderInterface.credentials(lines 25-28), which the loader uses to validate and map incoming values
Environment variables take precedence over the user settings file, allowing temporary overrides without modifying persistent storage.
Where OpenBB Stores API Keys
Understanding the physical storage locations helps implement proper security hygiene and .gitignore rules.
Environment Variables
OpenBB scans os.environ for any key ending with the suffix API_KEY. This convention allows the platform to automatically recognize provider credentials without explicit configuration. For example, setting export FRED_API_KEY="your_key" makes the Federal Reserve Economic Data provider immediately available.
User Settings File Location
The platform stores persistent credentials in ~/.openbb_platform/user_settings.json, defined in openbb_platform/core/openbb_core/app/constants.py (line 7) as USER_SETTINGS_PATH. This file is automatically created when you use the openbb config set CLI command or programmatically update settings.
The default location ensures the file resides outside version control directories, reducing the risk of accidental commits.
How to Configure API Keys in OpenBB
You can configure credentials through three methods, depending on your security requirements and deployment environment.
Method 1: Environment Variables (Preferred)
For production deployments and CI/CD pipelines, environment variables provide the most secure approach. They exist only in memory and never persist to disk in plain text within the project directory.
# Linux/macOS
export ALPHAVANTAGE_API_KEY="your_key_here"
export FRED_API_KEY="your_fred_key"
# Windows PowerShell
$env:ALPHAVANTAGE_API_KEY="your_key_here"
After setting these, OpenBB automatically detects them on the next initialization. No additional code is required to load these values.
Method 2: User Settings File
For local development where you want credentials to persist across sessions, use the user settings file. You can modify this file directly or use the CLI:
# Using OpenBB CLI
openbb config set credentials.alpha_vantage_api_key "your_key_here"
This command writes to ~/.openbb_platform/user_settings.json:
{
"credentials": {
"alpha_vantage_api_key": "your_key_here"
}
}
Method 3: Programmatic Configuration
For advanced use cases, you can directly manipulate the settings file using Python:
import json
from pathlib import Path
from openbb_core.app.constants import USER_SETTINGS_PATH
# Load existing settings or create new structure
settings_path = Path(USER_SETTINGS_PATH)
settings = {}
if settings_path.exists():
settings = json.loads(settings_path.read_text())
# Update credentials section
settings.setdefault("credentials", {})["alpha_vantage_api_key"] = "my-new-key"
settings_path.write_text(json.dumps(settings, indent=2))
print(f"Updated {USER_SETTINGS_PATH}")
Accessing and Using Credentials in Code
Once configured, accessing credentials in your OpenBB scripts is straightforward. The Credentials model handles all loading logic automatically.
Loading Credentials
from openbb_core.app.model.credentials import Credentials
# Automatically loads from env vars and user_settings.json
creds = Credentials()
# Access returns a SecretStr object, not the raw string
print(creds.alpha_vantage_api_key) # Output: **********
Retrieving Raw Values
When you need the actual key value (for example, to pass to a third-party library), use the get_secret_value() method:
# Safely extract the raw string when needed
plain_key = creds.alpha_vantage_api_key.get_secret_value()
print("Key length:", len(plain_key))
Displaying All Credentials
To audit which providers are configured without exposing values in logs, use the show() method:
# Display all configured credentials (masked by default)
Credentials().show()
According to the source code in credentials.py (lines 11-19), the show() method deliberately unmasks values only when explicitly requested and outputs a JSON-serialized view rather than raw secret objects.
Security Best Practices for OpenBB API Keys
Implementing proper security hygiene prevents credential leakage in version control or logs.
Conflict Resolution and Precedence
The CredentialsLoader implements a clear precedence order (lines 41-48 in credentials.py):
- Environment variables override user settings
- User settings provide fallback values
This hierarchy allows you to set permanent keys in user_settings.json while temporarily overriding them via environment variables for specific runs or CI/CD pipelines.
Never Commit Secrets
The OpenBB platform automatically stores user_settings.json outside your project directory in ~/.openbb_platform/, as defined in constants.py (line 7). This location is naturally excluded from Git repositories.
However, if you manually move or copy this file, ensure you:
- Add
*.jsonwith credential patterns to.gitignore - Never hard-code keys in Jupyter notebooks or Python scripts that might be shared
- Use environment variables for any repository-contained configuration examples
Summary
- OpenBB's
Credentialsmodel inopenbb_platform/core/openbb_core/app/model/credentials.pyautomatically loads API keys from environment variables and~/.openbb_platform/user_settings.json. - Environment variables ending with
API_KEYtake precedence over stored settings, enabling secure temporary overrides. - All credentials are typed as Pydantic
SecretStrto prevent accidental exposure in logs or print statements. - The
Credentials.show()method provides controlled access to credential status without exposing raw values by default. - Store sensitive keys in environment variables for production use, and rely on the user settings file only for local development persistence.
Frequently Asked Questions
Where does OpenBB store API keys locally?
OpenBB stores persistent API keys in ~/.openbb_platform/user_settings.json, as defined in openbb_platform/core/openbb_core/app/constants.py (line 7). This location resides in the user's home directory, outside of project repositories, to prevent accidental commits to version control. The file is created automatically when you use the openbb config set command or programmatically update credentials.
How do I override a stored API key temporarily?
Set an environment variable with the same name as the credential, ensuring it ends with API_KEY (e.g., export ALPHAVANTAGE_API_KEY="new_key"). According to the CredentialsLoader.load implementation in credentials.py (lines 41-48), environment variables automatically override values stored in user_settings.json. This approach is ideal for CI/CD pipelines or testing different keys without modifying your persistent configuration.
Is it safe to store API keys in user_settings.json?
Yes, provided you follow security best practices. The default location (~/.openbb_platform/user_settings.json) is outside typical Git repositories, reducing the risk of accidental commits. However, the file stores keys in plain text, so you should set appropriate file permissions (readable only by your user) and avoid copying this file to shared drives or cloud storage. For maximum security, prefer environment variables which exist only in memory.
How does OpenBB prevent accidental exposure of API keys?
OpenBB uses Pydantic's SecretStr type for all credential fields in the Credentials model, ensuring that values are masked as ********** when printed, logged, or converted to strings. The Credentials.show() method (lines 11-19 in credentials.py) provides controlled unmasking only when explicitly requested, outputting a JSON-serialized view rather than raw secret objects. This design prevents credentials from appearing in Jupyter notebook outputs, logs, or error tracebacks by default.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →