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

Concepts covered

pydantic-settings, BaseSettings, environment variables, .env