Configuration management helps your FastAPI app use settings like database info or secret keys safely and easily.
Configuration management in FastAPI
from pydantic import BaseSettings class Settings(BaseSettings): app_name: str admin_email: str items_per_user: int = 50 class Config: env_file = ".env" settings = Settings()
Use BaseSettings from Pydantic to define config variables.
Set env_file in Config to load variables from a file.
from pydantic import BaseSettings class Settings(BaseSettings): debug: bool = False database_url: str settings = Settings()
secret_key from a .env file automatically.from pydantic import BaseSettings class Settings(BaseSettings): secret_key: str class Config: env_file = ".env" settings = Settings()
settings = Settings(_env_file='.env.production')This FastAPI app uses configuration management to load settings from a .env file or environment variables. The endpoint returns these settings as JSON.
from fastapi import FastAPI from pydantic import BaseSettings class Settings(BaseSettings): app_name: str = "My FastAPI App" admin_email: str items_per_user: int = 10 class Config: env_file = ".env" settings = Settings() app = FastAPI() @app.get("/") async def read_root(): return { "app_name": settings.app_name, "admin_email": settings.admin_email, "items_per_user": settings.items_per_user }
Always keep your .env file out of version control to protect secrets.
You can override settings by setting environment variables directly.
Use type hints in BaseSettings to validate config values automatically.
Use pydantic.BaseSettings to manage FastAPI app configuration.
Load settings from environment variables or .env files for flexibility and security.
Access settings anywhere in your app by creating a settings instance.
Practice
pydantic.BaseSettings in a FastAPI application?Solution
Step 1: Understand the role of
pydantic.BaseSettingsBaseSettingsis designed to load configuration values from environment variables or .env files.Step 2: Differentiate from other FastAPI features
Database models, routing, and documentation are handled by other parts of FastAPI, notBaseSettings.Final Answer:
To manage application configuration using environment variables or .env files -> Option BQuick Check:
Configuration management = To manage application configuration using environment variables or .env files [OK]
- Confusing BaseSettings with database model classes
- Thinking BaseSettings handles API routing
- Assuming BaseSettings generates docs
pydantic.BaseSettings?Solution
Step 1: Check class inheritance
The settings class must inherit fromBaseSettingsto load environment variables.Step 2: Verify attribute definition
Attributes are defined as class variables with type annotations and default values.Final Answer:
class Settings(BaseSettings): app_name: str = "MyApp" -> Option DQuick Check:
Correct inheritance and attribute syntax = class Settings(BaseSettings): app_name: str = "MyApp" [OK]
- Using BaseModel instead of BaseSettings
- Defining settings as a function
- Incorrect inheritance or attribute assignment
API_KEY=secret123 set, what will print(settings.api_key) output?
from pydantic import BaseSettings
class Settings(BaseSettings):
api_key: str
settings = Settings()Solution
Step 1: Understand environment variable loading
BaseSettingsautomatically reads environment variables matching attribute names in uppercase.Step 2: Check if
The environment variableAPI_KEYis setAPI_KEY=secret123is set, sosettings.api_keywill be 'secret123'.Final Answer:
secret123 -> Option CQuick Check:
Env var API_KEY loads as 'secret123' [OK]
- Assuming missing default means None instead of error
- Thinking attribute names are case-sensitive differently
- Expecting empty string if env var is set
from pydantic import BaseSettings
class Settings(BaseSettings):
debug: bool = False
settings = Settings(debug="foo")Solution
Step 1: Check type of passed value
Thedebugattribute expects a boolean, but the code passes a string "foo".Step 2: Understand Pydantic validation
Pydantic tries to coerce the string to bool but "foo" is not recognized, causing a ValidationError.Final Answer:
Passing a string "foo" instead of a boolean causes a validation error -> Option AQuick Check:
Pydantic rejects invalid bool strings like "foo" [OK]
- Thinking Pydantic converts any string to bool
- Missing environment variable causes failure
- BaseSettings cannot have default values
.env file and override some values with environment variables in FastAPI. Which approach correctly achieves this using pydantic.BaseSettings?Solution
Step 1: Understand BaseSettings .env support
BaseSettingsloads .env files whenenv_file='.env'is set in the innerConfigclass.Step 2: Know environment variable precedence
Environment variables override .env file values automatically when both exist.Final Answer:
Create a Settings class inheriting BaseSettings withclass Config: env_file = '.env'and place a .env file in the project root; environment variables override .env values automatically -> Option AQuick Check:
BaseSettings loads .env via Config env_file and env vars override [OK]
- Manually parsing .env instead of using BaseSettings Config
- Using BaseModel which lacks .env support
- Thinking .env files are unsupported by BaseSettings
Ready to prove it?
Pass the test and this pattern moves unknown
