Configuration and settings management

Difficulty: Intermediate

Question

How do you manage configuration and environment variables in FastAPI?

Answer

The recommended approach is pydantic-settings (BaseSettings). It automatically reads from environment variables and .env files, validates them using Pydantic, and provides type-safe access.

BaseSettings fields:

  • Reads from environment variables by default (case-insensitive)
  • Falls back to .env file if configured
  • Type validation and defaults work the same as regular Pydantic models

Use @lru_cache on the settings function so the .env file is only parsed once, or use FastAPI's Depends with caching.

Code examples

Settings with pydantic-settings

# config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
from functools import lru_cache

class Settings(BaseSettings):
    app_name: str = "MyApp"
    database_url: str
    secret_key: str
    debug: bool = False
    max_connections: int = 10

    model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")

@lru_cache
def get_settings() -> Settings:
    return Settings()

# main.py
from fastapi import FastAPI, Depends
from config import Settings, get_settings

app = FastAPI()

@app.get("/info")
def app_info(settings: Settings = Depends(get_settings)):
    return {"app": settings.app_name, "debug": settings.debug}

Key points

  • Install with: `pip install pydantic-settings`
  • `@lru_cache` ensures the settings object is singleton - env/file is read only once
  • For testing, override `get_settings` via `app.dependency_overrides`

Common follow-up questions

  • How do you use different .env files for dev, staging, and production?
  • How do you handle secrets that should never be in .env files?

Interview tips

  • Always mention lru_cache - without it, the .env file is re-read on every request

Concepts covered

pydantic-settings, BaseSettings, environment variables, .env

More FastAPI Interview questions