File-Based Configuration¶
Learn how to load configuration from YAML, JSON, and TOML files.
Overview¶
Foundation supports loading configuration from files, making it easy to manage complex settings and environment-specific configurations.
YAML Configuration¶
# config.yaml
service:
name: my-app
version: 1.0.0
logging:
level: INFO
format: json
database:
host: localhost
port: 5432
pool_size: 10
from provide.foundation.config import ConfigManager
manager = ConfigManager()
config = await manager.load_yaml("config.yaml")
print(config["service"]["name"]) # "my-app"
JSON Configuration¶
{
"service": {
"name": "my-app",
"version": "1.0.0"
},
"logging": {
"level": "INFO",
"format": "json"
}
}
TOML Configuration¶
[service]
name = "my-app"
version = "1.0.0"
[logging]
level = "INFO"
format = "json"
[database]
host = "localhost"
port = 5432
pool_size = 10
Environment-Specific Files¶
import os
environment = os.getenv("ENVIRONMENT", "development")
config_file = f"config.{environment}.yaml"
config = await manager.load_yaml(config_file)
Merging Configurations¶
Combine multiple sources with environment variables taking precedence:
# Load base config
base_config = await manager.load_yaml("config.base.yaml")
# Load environment-specific overrides
env_config = await manager.load_yaml(f"config.{environment}.yaml")
# Merge (env_config overrides base_config)
final_config = {**base_config, **env_config}
Type-Safe Configuration¶
Use attrs classes for type safety:
from attrs import define
from provide.foundation.config import BaseConfig, env_field
@define
class ServiceConfig(BaseConfig):
name: str
version: str
port: int = 8000
# Load and validate
data = await manager.load_yaml("config.yaml")
service_config = ServiceConfig(**data["service"])
Next Steps¶
- Environment Variables - Environment-based config
- Secret Management - Secure configuration
- API Reference: Config - Complete config API