Bird
Raised Fist0
FastAPIframework~20 mins

Configuration management in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Configuration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this FastAPI configuration code?
Consider this FastAPI app configuration using Pydantic BaseSettings. What will be the value of app.state.config.debug after running this code?
FastAPI
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    debug: bool = False

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    app.state.config = Settings(debug=True)

# After startup event, what is app.state.config.debug?
AFalse
BTrue
CNone
DRaises AttributeError
Attempts:
2 left
💡 Hint
Think about when the startup event runs and how the Settings instance is created.
📝 Syntax
intermediate
2:00remaining
Which option correctly loads environment variables into FastAPI settings?
Given this Pydantic settings class, which option correctly loads environment variables from a file named .env?
FastAPI
from pydantic import BaseSettings

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

# How to load .env file automatically?
A
class Settings(BaseSettings):
    def __init__(self):
        self.env_file = ".env"
B
class Settings(BaseSettings):
    env_file = ".env"
C
class Settings(BaseSettings):
    class Config:
        env_file = ".env"
D
class Settings(BaseSettings):
    env_path = ".env"
Attempts:
2 left
💡 Hint
Pydantic uses a nested Config class for settings like env_file.
❓ state_output
advanced
2:00remaining
What is the value of config.app_name after this FastAPI app runs?
This FastAPI app uses a settings instance stored in app.state. What will config.app_name print?
FastAPI
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_name: str = "DefaultApp"

app = FastAPI()

@app.on_event("startup")
async def startup():
    app.state.config = Settings(app_name="CustomApp")

config = app.state.config
print(config.app_name)
AAttributeError because app.state.config is not set yet
BCustomApp
CDefaultApp
DNone
Attempts:
2 left
💡 Hint
Consider when app.state.config is set versus when config is assigned.
🔧 Debug
advanced
2:00remaining
Why does this FastAPI app fail to load environment variables?
This code tries to load environment variables but always uses default values. What is the cause?
FastAPI
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    debug: bool = False

    class Config:
        env_file = ".env"

app = FastAPI()

@app.on_event("startup")
async def startup():
    app.state.config = Settings()

# .env file contains DEBUG=true
AThe startup event runs too late to load environment variables
BPydantic BaseSettings does not support env_file
CThe debug field must be uppercase to load from .env
DThe .env file is not in the current working directory when app runs
Attempts:
2 left
💡 Hint
Check where the app runs and where the .env file is located.
🧠 Conceptual
expert
3:00remaining
Which is the best practice for managing configuration in a FastAPI app for multiple environments?
You want to manage different settings for development, testing, and production in FastAPI. Which approach is best?
AUse a single Pydantic BaseSettings class with environment variables loaded from different .env files per environment
BUse global variables and change them manually before running the app
CHardcode all settings in the app code and comment/uncomment per environment
DCreate separate FastAPI apps for each environment with duplicated code
Attempts:
2 left
💡 Hint
Think about maintainability and automation for different environments.

Practice

(1/5)
1. What is the primary purpose of using pydantic.BaseSettings in a FastAPI application?
easy
A. To generate API documentation
B. To manage application configuration using environment variables or .env files
C. To handle HTTP request routing
D. To create database models automatically

Solution

  1. Step 1: Understand the role of pydantic.BaseSettings

    BaseSettings is designed to load configuration values from environment variables or .env files.
  2. Step 2: Differentiate from other FastAPI features

    Database models, routing, and documentation are handled by other parts of FastAPI, not BaseSettings.
  3. Final Answer:

    To manage application configuration using environment variables or .env files -> Option B
  4. Quick Check:

    Configuration management = To manage application configuration using environment variables or .env files [OK]
Hint: Remember: BaseSettings is for config, not routing or DB [OK]
Common Mistakes:
  • Confusing BaseSettings with database model classes
  • Thinking BaseSettings handles API routing
  • Assuming BaseSettings generates docs
2. Which of the following is the correct way to define a FastAPI settings class using pydantic.BaseSettings?
easy
A. def Settings(): return BaseSettings(app_name="MyApp")
B. class Settings: app_name = BaseSettings("MyApp")
C. class Settings(BaseModel): app_name: str = "MyApp"
D. class Settings(BaseSettings): app_name: str = "MyApp"

Solution

  1. Step 1: Check class inheritance

    The settings class must inherit from BaseSettings to load environment variables.
  2. Step 2: Verify attribute definition

    Attributes are defined as class variables with type annotations and default values.
  3. Final Answer:

    class Settings(BaseSettings): app_name: str = "MyApp" -> Option D
  4. Quick Check:

    Correct inheritance and attribute syntax = class Settings(BaseSettings): app_name: str = "MyApp" [OK]
Hint: Settings class must inherit BaseSettings with typed attributes [OK]
Common Mistakes:
  • Using BaseModel instead of BaseSettings
  • Defining settings as a function
  • Incorrect inheritance or attribute assignment
3. Given this settings class and environment variable API_KEY=secret123 set, what will print(settings.api_key) output?
from pydantic import BaseSettings

class Settings(BaseSettings):
    api_key: str

settings = Settings()
medium
A. '' (empty string)
B. None
C. secret123
D. Raises a validation error

Solution

  1. Step 1: Understand environment variable loading

    BaseSettings automatically reads environment variables matching attribute names in uppercase.
  2. Step 2: Check if API_KEY is set

    The environment variable API_KEY=secret123 is set, so settings.api_key will be 'secret123'.
  3. Final Answer:

    secret123 -> Option C
  4. Quick Check:

    Env var API_KEY loads as 'secret123' [OK]
Hint: BaseSettings reads uppercase env vars matching attribute names [OK]
Common Mistakes:
  • Assuming missing default means None instead of error
  • Thinking attribute names are case-sensitive differently
  • Expecting empty string if env var is set
4. Identify the error in this FastAPI settings code snippet:
from pydantic import BaseSettings

class Settings(BaseSettings):
    debug: bool = False

settings = Settings(debug="foo")
medium
A. Passing a string "foo" instead of a boolean causes a validation error
B. Missing environment variable causes failure
C. BaseSettings cannot have default values
D. Class must inherit from BaseModel, not BaseSettings

Solution

  1. Step 1: Check type of passed value

    The debug attribute expects a boolean, but the code passes a string "foo".
  2. Step 2: Understand Pydantic validation

    Pydantic tries to coerce the string to bool but "foo" is not recognized, causing a ValidationError.
  3. Final Answer:

    Passing a string "foo" instead of a boolean causes a validation error -> Option A
  4. Quick Check:

    Pydantic rejects invalid bool strings like "foo" [OK]
Hint: Pydantic bool fields reject invalid strings like "foo" [OK]
Common Mistakes:
  • Thinking Pydantic converts any string to bool
  • Missing environment variable causes failure
  • BaseSettings cannot have default values
5. You want to load configuration from a .env file and override some values with environment variables in FastAPI. Which approach correctly achieves this using pydantic.BaseSettings?
hard
A. Create a Settings class inheriting BaseSettings with class Config: env_file = '.env' and place a .env file in the project root; environment variables override .env values automatically
B. Manually read .env file with open() and parse it, then pass values to Settings constructor
C. Use BaseModel instead of BaseSettings and load .env with dotenv package separately
D. Set environment variables only; .env files are not supported by BaseSettings

Solution

  1. Step 1: Understand BaseSettings .env support

    BaseSettings loads .env files when env_file='.env' is set in the inner Config class.
  2. Step 2: Know environment variable precedence

    Environment variables override .env file values automatically when both exist.
  3. Final Answer:

    Create a Settings class inheriting BaseSettings with class Config: env_file = '.env' and place a .env file in the project root; environment variables override .env values automatically -> Option A
  4. Quick Check:

    BaseSettings loads .env via Config env_file and env vars override [OK]
Hint: BaseSettings loads .env via Config(env_file='.env'); env vars override .env values [OK]
Common Mistakes:
  • Manually parsing .env instead of using BaseSettings Config
  • Using BaseModel which lacks .env support
  • Thinking .env files are unsupported by BaseSettings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard