FastAPI: Managing Environment-Specific Settings
Treat app configuration like a contract, not hardcoded values. Pydantic Settings defines required variables (like API keys) and loads them from the environment, preventing you from shipping dev settings to production.
Why it exists
Applications need to run in different environments (local, staging, production) which require different configurations, like database URLs or API keys. Hardcoding these values is insecure and inflexible. A systematic way to manage these settings is needed to prevent errors and security leaks.
The mental model
Think of your application's configuration as a typed contract. You declare all the external settings your app needs in a single Pydantic BaseSettings class. This class acts as a single source of truth, defining the setting's name, type, and default value. FastAPI then automatically populates this object from environment variables or a .env file.
How it works
You create a class that inherits from pydantic_settings.BaseSettings. Inside, you define attributes with type hints, like database_url: str. Pydantic Settings reads environment variables that match your attribute names (case-insensitively). For example, an environment variable DATABASE_URL will populate the database_url attribute. It can also automatically load these from a .env file if one is present. This gives you type-validated, centrally-managed settings that raise an error on startup if a required value is missing.
When to use it
Use this for any value that changes between deployments. This includes database connection strings, external API keys, secret keys for signing tokens, log levels (e.g., 'DEBUG' vs. 'INFO'), and feature flags. It's standard practice for any non-trivial FastAPI application.
When not to use it
Avoid using it for true application constants that never change, like a mathematical constant or a fixed algorithm parameter. These can be defined directly in your code as uppercase constants. Overusing it for static values can make the code harder to follow by hiding simple constants behind an environment loading mechanism.
One canonical example
First, create a config.py file and define a settings class: from pydantic_settings import BaseSettings followed by class Settings(BaseSettings): app_name: str = "My API"; admin_email: str; database_url: str; class Config: env_file = ".env". Then, instantiate it: settings = Settings(). Next, create a .env file in your project root with the content: ADMIN_EMAIL=dev@example.com and DATABASE_URL=postgresql://user:pass@localhost/db. Now, in your main app, you can from config import settings and access validated values like settings.admin_email. Pydantic raises an error if required settings are missing.
Interview question
Which scenario best illustrates the appropriate use of Pydantic Settings in a FastAPI application?
- a.Managing a list of static, hardcoded error messages displayed to users.
- b.Validating the structure and types of incoming JSON request bodies for an API endpoint.
- c.Storing a database connection string that differs between development, staging, and production environments.Correct
- d.Defining a fixed mathematical constant like PI for calculations within the application.
Why? this is the answer
Pydantic Settings is specifically designed to manage configuration values that vary across different deployment environments, such as database URLs or API keys, ensuring they are loaded securely and validated. While Pydantic is used for request body validation, Pydantic Settings focuses on environment-dependent application settings, not static constants or request schemas.
Just read this? Test yourself on what you have been reading.
Read the original → fastapi.tiangolo.com
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on python — each one lists the topics its interview covers.
See open roles