| name | pydantic-settings-management |
| description | Guides the professional implementation of application configuration using pydantic-settings and .env files.
Use when the user needs to manage environment variables, validate config schemas,
or structure settings for agents and web apps (FastAPI, etc.).
|
Pydantic Settings & Env Management
This skill provides a standardized, type-safe workflow for managing application configuration in 2025.
Workflow Summary
- Isolation: Use
.env for local secrets; never commit it to git.
- Validation: Use
BaseSettings to enforce types (e.g., ensure PORT is an int).
- Singleton Pattern: Instantiate settings once in a
config.py and import the instance.
Implementation Guide
1. Environment File (.env)
Store your keys in a standard .env format at the project root.
# .env
DEBUG=true
PORT=8000
API_KEY=sk-your-key-here
2. Configuration Schema
Define your settings in a dedicated config.py file.
from pydantic_settings import BaseSettings, SettingsConfigDict
class AppSettings(BaseSettings):
api_key: str
port: int = 8000
debug: bool = False
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False
)
settings = AppSettings()
3. Usage in Application
Always import the settings instance, not the class.
from config import settings
def start_server():
if settings.debug:
print(f"Starting in DEBUG mode on port {settings.port}")
Advanced Patterns
For complex integrations (Prefixes, Nested Models, or Secrets Directories), refer to the bundled documentation:
references/advanced_config.md
Common Troubleshooting
| Error | Cause | Solution |
|---|
| ValidationError | Missing or wrong type in .env | Check that PORT is a number and required keys exist. |
| ModuleNotFoundError | pydantic-settings missing | Run uv add pydantic-settings. |
| .env not loading | Wrong file path | Set env_file=".env" in SettingsConfigDict. |
| Third-party SDK can't find env var | pydantic-settings reads .env into object, not os.environ | Export to os.environ in __init__ (see pitfall below) |
Pitfall: Third-Party SDKs That Read os.environ
pydantic-settings reads .env into Settings object properties but does NOT export them to os.environ. SDKs like OpenAI, Stripe, and others that read directly from os.environ will fail with "API key not set" errors even though the key is in .env.
Fix: Bridge the gap in __init__:
class Settings(BaseSettings):
openai_api_key: str = ""
stripe_secret_key: str = ""
def __init__(self, **kwargs):
import os
super().__init__(**kwargs)
if self.openai_api_key and not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = self.openai_api_key
if self.stripe_secret_key and not os.environ.get("STRIPE_SECRET_KEY"):
os.environ["STRIPE_SECRET_KEY"] = self.stripe_secret_key
The not os.environ.get(...) guard avoids overwriting explicitly set env vars (e.g., from Docker/CI).
Resources
references/advanced_config.md
Documentation for advanced configuration patterns including environment prefixes, nested settings, and secret masking.