Complete the code to import the BaseSettings class from Pydantic for configuration.
from pydantic import [1]
The BaseSettings class from Pydantic is used to define configuration classes that read environment variables automatically.
Complete the code to define a configuration class that reads the app name from environment variables.
class Settings(BaseSettings): app_name: str = [1]
The default value for app_name is set to "FastAPI App" here, which will be used if no environment variable overrides it.
Fix the error in the code to create a singleton settings instance for reuse.
def get_settings(): if not hasattr(get_settings, "_settings"): get_settings._settings = [1]() return get_settings._settings
The function creates a single instance of the Settings class and reuses it to avoid recreating settings multiple times.
Fill both blanks to load environment variables from a .env file using Pydantic settings.
class Settings(BaseSettings): class Config: env_file = [1] env_file_encoding = [2]
The env_file is set to ".env" to load environment variables from that file, and env_file_encoding is set to "utf-8" to properly read the file encoding.
Fill all three blanks to create a FastAPI app that uses dependency injection to get settings.
from fastapi import FastAPI, Depends app = FastAPI() @app.get("/") async def read_root(settings: Settings = Depends([1])): return {"app_name": settings.[2] settings_instance = [3]()
The endpoint uses FastAPI's Depends to inject the singleton settings instance returned by get_settings. The response returns the app_name attribute from the settings. The settings_instance is created by instantiating the Settings class.