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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
