Skip to main content

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 .env file to Git! It contains sensitive credentials. Always add .env to your .gitignore file. Instead, commit a .env.example file 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-in os.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 from pydantic_settings.BaseSettings. Pydantic will automatically load fields from environment variables (case-insensitive) and validate their types.

Accessing Settings in Your App

Now, import settings anywhere in your application: