Environment-based settings help your app use different values depending on where it runs, like your computer or a server. This keeps your app flexible and safe.
Environment-based settings in FastAPI
from pydantic import BaseSettings class Settings(BaseSettings): app_name: str debug: bool = False database_url: str class Config: env_file = ".env" settings = Settings()
Use BaseSettings from Pydantic to define environment-based settings easily.
The env_file option tells Pydantic to load variables from a file named .env.
database_url from environment.class Settings(BaseSettings): app_name: str = "My FastAPI App" debug: bool = True database_url: str class Config: env_file = ".env"
settings = Settings() print(settings.app_name) print(settings.debug) print(settings.database_url)
# .env file content APP_NAME=AwesomeAPI DEBUG=False DATABASE_URL=postgresql://user:pass@localhost/dbname
This FastAPI app reads settings from environment or .env file and shows them at the root URL.
from fastapi import FastAPI from pydantic import BaseSettings class Settings(BaseSettings): app_name: str = "FastAPI Example" debug: bool = False database_url: str class Config: env_file = ".env" settings = Settings() app = FastAPI() @app.get("/") def read_root(): return { "app_name": settings.app_name, "debug_mode": settings.debug, "database_url": settings.database_url }
Always keep your .env file out of version control to protect secrets.
You can override environment variables by setting them directly in your system or deployment platform.
Use boolean fields carefully; environment variables are strings, so Pydantic converts them automatically.
Environment-based settings let your app change behavior without code changes.
Use Pydantic's BaseSettings and a .env file for easy setup.
Keep secrets safe and make your app flexible for different environments.
Practice
Solution
Step 1: Understand environment-based settings concept
Environment-based settings allow configuration changes without changing the code itself.Step 2: Identify the main benefit in FastAPI
This lets the app behave differently in development, testing, or production by just changing environment variables.Final Answer:
To change app behavior without modifying the code -> Option AQuick Check:
Environment-based settings = change behavior without code change [OK]
- Confusing settings with performance improvements
- Thinking it automatically adds routes
- Assuming it creates UI elements
Solution
Step 1: Recall correct base class for environment settings
Pydantic's BaseSettings is designed for environment-based config loading.Step 2: Check class definition syntax
Using BaseSettings with typed attributes and default values is correct.Final Answer:
class Settings(BaseSettings):\n debug: bool = False -> Option BQuick Check:
Use BaseSettings for env config classes [OK]
- Using BaseModel instead of BaseSettings
- Inheriting from dict or object directly
- Missing type annotations
settings.debug?
class Settings(BaseSettings):
debug: bool = False
settings = Settings()
.env file content:
DEBUG=true
Solution
Step 1: Understand BaseSettings behavior with .env
BaseSettings reads environment variables and overrides defaults if present.Step 2: Check .env value for DEBUG
The .env file sets DEBUG=true, which overrides the default False.Final Answer:
True -> Option CQuick Check:
.env overrides default values in BaseSettings [OK]
- Assuming default stays despite .env
- Confusing string 'true' with boolean
- Expecting error if .env exists
from pydantic import BaseSettings
class Settings(BaseSettings):
api_key: str
settings = Settings()
Assuming no environment variable API_KEY is set.Solution
Step 1: Check required fields in BaseSettings
Fields without defaults are required and must be provided via env or arguments.Step 2: Consider missing environment variable
Since API_KEY is not set, BaseSettings raises a validation error on instantiation.Final Answer:
It will raise a validation error because api_key is required but missing -> Option DQuick Check:
Missing required env vars cause validation errors [OK]
- Expecting default empty string or None
- Thinking missing vars are ignored
- Assuming no error on missing required field
Solution
Step 1: Understand default values with environment override
Using a default value directly allows configuration from environment variables if present, falling back to the default otherwise.Step 2: Compare options for correct default and override behavior
class Settings(BaseSettings):\n database_url: str = 'sqlite:///default.db' uses a direct default value, overridden by DATABASE_URL env var if set.Final Answer:
class Settings(BaseSettings):\n database_url: str = 'sqlite:///default.db' -> Option AQuick Check:
Direct default = env override if present [OK]
- Leaving field required without default
- Using Field(default_factory=...) unnecessarily (requires Field import)
- Using Optional[str] = None (defaults to None)
Ready to prove it?
Pass the test and this pattern moves unknown
