Python / FastAPI Basics Interview Questions
How do you manage environment variables and settings in FastAPI with Pydantic Settings?
Use pydantic-settings to define a typed settings class that reads from environment variables and .env files. Inject settings via a dependency so they can be overridden in tests.
# pip install pydantic-settings from pydantic_settings import BaseSettings, SettingsConfigDict from functools import lru_cache from fastapi import FastAPI, Depends from typing import Annotated class Settings(BaseSettings): app_name: str = "My API" debug: bool = False db_url: str = "sqlite:///./test.db" secret_key: str jwt_expire_minutes: int = 30 model_config = SettingsConfigDict( env_file=".env", # read from .env file env_file_encoding="utf-8", case_sensitive=False, # DB_URL and db_url both work ) @lru_cache # singleton â reads .env once, cached for app lifetime def get_settings() -> Settings: return Settings() SettingsDep = Annotated[Settings, Depends(get_settings)] app = FastAPI() @app.get("/info") def app_info(settings: SettingsDep): return {"app_name": settings.app_name, "debug": settings.debug}
# .env file (never commit to git) SECRET_KEY=my-super-secret-key-here DB_URL=postgresql+asyncpg://user:pass@localhost/mydb DEBUG=false
# tests â override settings easily from app.main import app, get_settings from app.config import Settings def override_settings(): return Settings(secret_key="test-key", db_url="sqlite:///./test.db") app.dependency_overrides[get_settings] = override_settings
More Related questions...