Create the Settings Class
Exit

Create the Settings Class

Define a Settings class that reads configuration from environment variables

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

How BaseSettings works

Pydantic's BaseSettings works like BaseModel, but instead of reading data from a request body, it reads data from environment variables. Each field in the class maps to an environment variable with the same name.

class Settings(BaseSettings):
    data_file: str = "expenses.json"

When you create a Settings() instance, Pydantic checks for an environment variable named DATA_FILE. If it finds one, it uses that value. If not, it falls back to the default value "expenses.json".

The .env file

Instead of setting environment variables in the shell, you can put them in a .env file in your project directory:

DATA_FILE=production_expenses.json
APP_TITLE=Expense Tracker API

Adding model_config = SettingsConfigDict(env_file=".env") tells Pydantic to read from this file automatically. Environment variables set in the shell take priority over values in the .env file.

Install pydantic-settings

BaseSettings lives in a separate package called pydantic-settings. You need to install it with pip install pydantic-settings before importing it. If you are following along in your own environment, run that command first.

Instructions

Add a Settings class to your API.

  1. Add from pydantic_settings import BaseSettings, SettingsConfigDict to the imports.
  2. After the models (after the ErrorResponse class), define a class called Settings that inherits from BaseSettings. Inside it, add:
    • data_file: str = "expenses.json"
    • app_title: str = "FastAPI"
    • model_config = SettingsConfigDict(env_file=".env")
  3. After the class definition, create a settings instance with settings = Settings().