Skip to main content
Most applications need external settings and configurations like secret keys, database credentials, API tokens, and other environment-specific values. FastAPI integrates seamlessly with Pydantic Settings to provide type-safe, validated configuration management.

Why Use Settings Management?

Environment variables are essential for:
  • Security: Keeping secrets out of your codebase
  • Flexibility: Different settings for development, staging, and production
  • Portability: Easy deployment across different environments
  • 12-Factor App compliance: Following modern application best practices
Never hardcode sensitive information like passwords, API keys, or secret tokens in your source code. Always use environment variables or secure configuration management.

Understanding Environment Variables

Environment variables are text strings stored outside your application code. They’re accessible to your application at runtime but can only be read as strings.

The Challenge

This is where Pydantic Settings comes in.

Pydantic Settings

Pydantic Settings provides automatic type conversion, validation, and IDE support for your application configuration.

Installation

First, install the pydantic-settings package:
Or install it with FastAPI’s all extras:
The pydantic-settings package is a separate package from Pydantic itself and must be installed explicitly.

Creating a Settings Class

Create a settings class by inheriting from BaseSettings:
Pydantic Settings will:
  • ✅ Read environment variables (case-insensitive)
  • ✅ Convert types automatically (string → int, bool, etc.)
  • ✅ Validate required fields
  • ✅ Use default values when not provided
  • ✅ Raise errors for invalid data

Using Settings in FastAPI

Here’s a complete example:

Running with Environment Variables

Environment variable names are matched to field names in a case-insensitive manner. APP_NAME, app_name, and App_Name all map to the app_name field.

Organizing Settings in Modules

For larger applications, separate your settings into dedicated modules.

config.py

main.py

Settings as Dependencies

Using settings as a dependency makes testing easier and provides better control:
The @lru_cache decorator ensures the settings are only loaded once, improving performance. Without it, settings would be reloaded on every request.

Benefits of Dependency Injection

  1. Easier testing: Override settings in tests
  2. Better isolation: Each test can have different settings
  3. Explicit dependencies: Clear what each endpoint needs

Testing with Settings Dependencies

Reading from .env Files

For local development, you can store environment variables in a .env file.

Creating a .env File

Configuring Settings to Read .env

Install python-dotenv:
Update your settings class:
Now Pydantic will automatically load variables from the .env file.
Never commit your .env file to version control. Add it to your .gitignore file to prevent accidentally exposing secrets.

Multiple Environment Files

You can use different .env files for different environments:
Then use:
  • .env.development for local development
  • .env.staging for staging environment
  • .env.production for production

Optimizing Settings Loading with lru_cache

Reading settings (especially from files) is expensive. Use @lru_cache to load them only once:

How lru_cache Works

@lru_cache is from Python’s functools module. It caches function results based on arguments. Since get_settings() has no arguments, it always returns the same cached result.

Advanced Configuration

Field Validation

Environment Variable Prefixes

Use prefixes to namespace your environment variables:

Nested Settings

Use double underscores __ to set nested configuration values via environment variables.

Real-World Example

Here’s a complete, production-ready settings configuration:

Best Practices

1. Use Type Hints

2. Provide Sensible Defaults

3. Use Field Validators

4. Document Your Settings

5. Never Commit Secrets

Add to .gitignore:

Deployment Considerations

Container Environments (Docker, Kubernetes)

Cloud Platforms (AWS, GCP, Azure)

Most cloud platforms provide environment variable management:
  • AWS: Parameter Store, Secrets Manager
  • GCP: Secret Manager
  • Azure: Key Vault
  • Heroku: Config Vars
Always use your platform’s secret management service for sensitive data in production.

Summary

Pydantic Settings provides: Type safety: Automatic type conversion and validation ✅ IDE support: Full autocomplete and type checking
Easy testing: Dependency injection for test overrides ✅ File support: Read from .env files ✅ Performance: Cache with @lru_cacheValidation: Field validators and constraints

Learn More

Settings management is crucial for production applications. Always validate and type-check your configuration to catch errors early.