0
0
FastapiHow-ToBeginner · 4 min read

How to Use Pydantic Settings with FastAPI for Configuration

Use pydantic.BaseSettings to define configuration classes that automatically read environment variables in FastAPI. Instantiate your settings class once and use it throughout your app to access config values safely and clearly.
📐

Syntax

Define a class inheriting from pydantic.BaseSettings. Declare your configuration variables as class attributes with types. Optionally, use Field to set defaults or environment variable names. Instantiate this class to load settings from environment variables automatically.

python
from pydantic import BaseSettings, Field

class Settings(BaseSettings):
    app_name: str = Field(default="My FastAPI App", env="APP_NAME")
    debug: bool = Field(default=False, env="DEBUG")
    database_url: str

settings = Settings()
💻

Example

This example shows a FastAPI app using Pydantic Settings to load configuration from environment variables. The Settings class reads APP_NAME, DEBUG, and DATABASE_URL. The app uses these values in a route.

python
from fastapi import FastAPI
from pydantic import BaseSettings, Field

class Settings(BaseSettings):
    app_name: str = Field(default="My FastAPI App", env="APP_NAME")
    debug: bool = Field(default=False, env="DEBUG")
    database_url: str

settings = Settings()

app = FastAPI()

@app.get("/")
def read_root():
    return {
        "app_name": settings.app_name,
        "debug_mode": settings.debug,
        "database_url": settings.database_url
    }
Output
{"app_name": "My FastAPI App", "debug_mode": false, "database_url": "postgresql://user:pass@localhost/db"}
⚠️

Common Pitfalls

  • Not setting required environment variables causes validation errors at startup.
  • Forgetting to instantiate the settings class once and reusing it can cause inconsistent config.
  • Using plain BaseModel instead of BaseSettings will not load environment variables automatically.
  • Not specifying env in Field when environment variable names differ from attribute names.
python
from pydantic import BaseModel

# Wrong: BaseModel does not load env vars automatically
class WrongSettings(BaseModel):
    database_url: str

wrong_settings = WrongSettings(database_url="default")  # Does not read env vars

from pydantic import BaseSettings

# Right: BaseSettings reads env vars
class CorrectSettings(BaseSettings):
    database_url: str

correct_settings = CorrectSettings()  # Reads from env vars
📊

Quick Reference

ConceptDescriptionExample
BaseSettingsBase class to create settings that read environment variablesclass Settings(BaseSettings): ...
Field with envSet environment variable name if different from attributeapp_name: str = Field(env="APP_NAME")
InstantiationCreate one instance to use app-widesettings = Settings()
Required fieldsFields without defaults must be set in env varsdatabase_url: str
Usage in FastAPIAccess settings instance in routes or startupsettings.app_name

Key Takeaways

Use pydantic.BaseSettings to define config classes that auto-load environment variables.
Instantiate your settings class once and reuse it across your FastAPI app.
Use Field(env="VAR_NAME") to map environment variables to different attribute names.
Required fields without defaults must be set in environment variables or app will error.
Avoid using BaseModel for settings because it does not load environment variables automatically.