1. Environment Variables (.env)
An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. In backend development, we use them to store:- API Keys and secrets
- Database connection strings (URLs)
- Application ports and modes (e.g., debug vs. production)
The .env File
Instead of hardcoding configurations in our code, we save them in a local text file named .env:
[!CAUTION] Never commit your.envfile to Git! It contains sensitive credentials. Always add.envto your.gitignorefile. Instead, commit a.env.examplefile that lists the keys but leaves the values blank.
2. Managing Settings with Pydantic Settings
While you can access environment variables using Python’s built-inos.environ.get(), it does not validate data types or check if required fields are missing.
The industry-standard way to manage configuration in FastAPI is using pydantic-settings.
Installation
Creating a Settings Config
Inherit frompydantic_settings.BaseSettings. Pydantic will automatically load fields from environment variables (case-insensitive) and validate their types.
Accessing Settings in Your App
Now, importsettings anywhere in your application: