Learn / Frameworks / FastAPI / Settings with pydantic-settings

FastAPI · Lesson 10 of 15

Settings with pydantic-settings

Load config from the environment, keep secrets out of code and cache settings.

  • Intermediate
  • 14 min read
  • 3 objectives

Before this lessonLesson 9: Testing with TestClient

What you will learn

  • Define a Settings class
  • Read env vars
  • Inject settings with Depends

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Configuration belongs in the environment. pydantic-settings maps env vars onto a typed class and fails fast if a required secret is missing.

A Settings class

# pip install pydantic-settings
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env", extra="ignore")
    env: str = "dev"
    database_url: str
    secret_key: str
    cors_origins: list[str] = ["http://localhost:5173"]

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

def get_db_url(settings: Settings = Depends(get_settings)) -> str:
    return settings.database_url

SECRET_KEY in the environment becomes secret_key on the class. Nested lists can be JSON in the env var.

Using it at startup

settings = get_settings()
app = FastAPI(title="Tasks", debug=settings.env == "dev")
Up next · Lesson 11Background Tasks and WebSocketsRun work after the response and push events over a WebSocket.