settings.api_key if the environment variable API_KEY is set to secret123?from pydantic import BaseSettings class Settings(BaseSettings): api_key: str settings = Settings()
The Settings class inherits from BaseSettings, which reads environment variables matching the attribute names in uppercase. Since API_KEY is set in the environment, settings.api_key will have the value "secret123".
DATABASE_URL?from pydantic import BaseSettings class Settings(BaseSettings): database_url: str settings = Settings()
Option A correctly uses a type annotation database_url: str and creates an instance with Settings(). Option A assigns the type to the variable, which is incorrect. Option A sets a default None which is invalid for a required str without Optional. Option A misses parentheses when instantiating.
settings = Settings() but the environment variable SECRET_KEY is not set?from pydantic import BaseSettings class Settings(BaseSettings): secret_key: str settings = Settings()
Since secret_key is required and no default is provided, and the environment variable SECRET_KEY is missing, Pydantic raises a ValidationError when creating the Settings instance.
from fastapi import FastAPI from pydantic import BaseSettings class Settings(BaseSettings): app_name: str = "MyApp" settings = Settings() app = FastAPI() @app.get("/") def read_root(): return {"app_name": settings.app_name}
BaseSettings reads environment variables from the OS environment or a .env file in the working directory. If the .env file is missing or environment variables are not set, default values are used. The likely cause is missing environment variables or .env file.
timeout: int = 30, and an environment variable TIMEOUT=60 set, what will be the value of settings.timeout after instantiation?from pydantic import BaseSettings class Settings(BaseSettings): timeout: int = 30 settings = Settings()
Pydantic BaseSettings uses environment variables to override default values. Since TIMEOUT=60 is set in the environment, settings.timeout will be 60, not the default 30.