0
0
FastapiHow-ToBeginner · 4 min read

How to Use Pydantic Settings in FastAPI for Configuration

Use pydantic.BaseSettings to define configuration classes that load environment variables automatically. In FastAPI, create a settings instance and use it to access config values safely throughout your app.
📐

Syntax

Define a class inheriting from pydantic.BaseSettings. Declare your configuration variables as class attributes with types. Pydantic loads values from environment variables matching attribute names by default.

Use Config inner class to customize behavior like environment variable prefixes.

python
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_name: str
    debug: bool = False
    database_url: str

    class Config:
        env_prefix = 'MYAPP_'

settings = Settings()
💻

Example

This example shows how to define settings with BaseSettings, load environment variables, and use the settings in a FastAPI app.

python
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_name: str = "My FastAPI App"
    debug: bool = False
    database_url: str

    class Config:
        env_prefix = 'MYAPP_'

settings = Settings()

app = FastAPI()

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

Common Pitfalls

  • Not setting environment variables correctly or forgetting the prefix causes default values or errors.
  • Using mutable defaults or missing type annotations can cause unexpected behavior.
  • Creating multiple Settings instances can lead to inconsistent config; use a single shared instance.
python
from pydantic import BaseSettings

# Wrong: mutable default and no type
class BadSettings(BaseSettings):
    items = []  # mutable default, avoid

# Right: use type and default factory
from typing import List
from pydantic import Field

class GoodSettings(BaseSettings):
    items: List[str] = Field(default_factory=list)
📊

Quick Reference

Tips for using Pydantic Settings in FastAPI:

  • Use BaseSettings to auto-load env vars.
  • Set env_prefix to avoid conflicts.
  • Access settings via a single instance.
  • Use type hints for validation and clarity.
  • Override defaults with environment variables for flexibility.

Key Takeaways

Use pydantic.BaseSettings to define typed config that loads from environment variables automatically.
Create one shared settings instance to use throughout your FastAPI app for consistent config access.
Set env_prefix in Config to namespace environment variables and avoid collisions.
Always use type annotations and avoid mutable default values in settings classes.
Override default values by setting environment variables before running your FastAPI app.