FastAPI Pydantic Settings Complete Guide to Multi-Environment Configuration
📂 Phase: Phase 5 - Engineering and Deployment (Practical) 🔗 Related Chapters: FastAPIdependency-injection · FastAPI安全认证
Table of contents
Environment Configuration Management Overview
Have you ever encountered such a situation: everything was normal when debugging with SQLite during local development, but after pushing to the server, because the database URL was not modified in time, the production environment was also connected to the development library, and the test data was even accidentally written into the official database? This is a classic disaster caused by "hard-coded configuration".
Dangers of hard-coded configuration:
- It is easy to forget to modify when switching environments
- Sensitive information such as keys and passwords may be leaked to the warehouse
- Code is not reusable in different environments
Following the configuration principle of 12-Factor App, we should completely separate configuration from code and dynamically inject it through environment variables or configuration files. The benefits of doing this are very obvious:
- Environment Isolation: Development, testing, and production environments do not interfere with each other
- Security Protection: Sensitive information such as passwords and keys will not be hard-coded in the code
- Flexible deployment: Environment switching can be completed without modifying a line of code
💡 Actual combat comparison The following example shows the problem of hard-coded configuration and how to avoid it with environment-driven configuration.
By reading different environment files, the application no longer needs to care about which environment it is in, and the code can truly remain unchanged and the configuration can be changed.
Pydantic Settings Basics
Pydantic Settings is a configuration artifact in the FastAPI ecosystem. It is based on Pydantic's data verification capabilities, which can help you read environment variables or configuration files in a type-safe manner, and supports automatic verification.
Install
Define basic configuration classes
Let's first create aBaseConfig, put the configuration items common to all environments here. passmodel_configSpecify the default environment file name and prohibit undefined extra fields to avoid configuration confusion.
Environment-specific configuration classes
through inheritanceBaseConfig, we create separate configuration classes for the development environment and production environment respectively. Production environments need to turn off debugging options, use a more robust database, and even add additional validation rules.
Configuration factory: automatically loaded according to environment
We write a factory function based onENVIRONMENTThe value of the environment variable loads the corresponding configuration class. In order to improve performance, also uselru_cacheCache configuration instances to avoid repeated initialization.
In a FastAPI application, you can easily use dependency injection to obtain configuration:
Multi-environment configuration strategy
Pydantic Settings follows an explicit priority when reading configuration. This feature allows us to override settings in a more flexible way.
Environment variable priority (from high to low)
- Directly pass parameters to the configuration class (such as
Config(key="value")) - System environment variables
.envdocument- Field default value
This means: even if.envset in the fileDEBUG=true, if you pass in the startup commandexport DEBUG=falseOverride, the program will use the value of the system environment variable first.
Use different.envdocument
Have a dedicated one for each environment.envDocumentation is a good practice. Example of file content:
SECURITY WARNING: ALL.envAll files should be added.gitignore, to prevent sensitive information from being submitted to version control. But you can create aenv.exampleTemplate for team members to refer to.
Docker multi-environment deployment
In Docker or Docker Compose, you can doenv_fileSpecify an environment file or directly inject environment variables. Here is a typical development/production configuration:
You can switch by specifying environment variables at startup:
Configuration validation and type safety
One of Pydantic’s trump cards is its powerful type validation. Not only can we limit field types, we can also use enumerations and literal types to make the meaning of the configuration clearer and avoid spelling errors.
In this way, incorrect configuration values will throw an exception immediately when the application starts, truly achieving "early detection and early repair".
Sensitive information security management
Sensitive information (database passwords, JWT keys, third-party API keys) must be kept secure. Pydantic Settings fully supports reading from external Secret stores.
Best Practices for Key Management
- Local Development: Use
.envfile and exclude the file from version control - Production environment: Use Docker Secrets, Kubernetes Secrets or cloud platform key management services (such as AWS Secrets Manager)
- Never Hardcode: Clear text keys should not appear anywhere in the code
Secure key reading function
You can write a helper function that first reads the secret from the directory where Docker Secrets is mounted, and then obtains it from environment variables.
In a configuration class you can use it like this:
Production deployment best practices
Security checklist before going live
Be sure to confirm each item before deployment:
-
DEBUG=False, never enable debugging mode in the production environment - Use a strong key of at least 64 characters (available via
openssl rand -hex 32generate) - CORS whitelist is limited to specific production domain names, no wildcards are used
- Database uses PostgreSQL/MySQL and enables SSL connection
- log level set to
WARNINGor higher to avoid outputting sensitive information - All sensitive information is injected through Secrets, not hard-coded in images or environment files
Automated deployment script example
The following script will first check the necessary environment variables, then build and start the service based on Docker Compose, and perform a simple health check.
Summarize
FastAPI and Pydantic Settings provide a rigorous and easy-to-use configuration management solution. The core advantages include:
- Environmental Isolation: Passed
.envSwitch files or environment variables to keep your code pure - Type Safety: Complete type hints and verification mechanisms to eliminate runtime configuration errors
- Worry-free security: Sensitive information can be completely separated from the code, matching cloud native security practices
- Cloud-native friendly: Perfectly adapted to containerized platforms such as Docker and Kubernetes
💡 Key Points: Establishing a good configuration management system at the beginning of the project can pave the way for subsequent continuous integration, multi-environment deployment, and security compliance. Every minute you spend on configuration management will save you a lot of maintenance time later.
🔗 Extended reading

