Bird
Raised Fist0
FastAPIframework~20 mins

Environment-based settings in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Environment Settings Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
How does FastAPI behave with environment-based settings?
Given a FastAPI app that loads settings from environment variables using Pydantic's BaseSettings, what will be the output when accessing the `/info` endpoint if the environment variable `APP_MODE` is set to `production`?
FastAPI
from fastapi import FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_mode: str = "development"

    class Config:
        env_prefix = "APP_"

settings = Settings()
app = FastAPI()

@app.get("/info")
async def get_info():
    return {"mode": settings.app_mode}
A{"mode": "production"}
B{"mode": "development"}
C{"mode": "APP_production"}
D{"mode": null}
Attempts:
2 left
💡 Hint
Remember that Pydantic BaseSettings reads environment variables with the prefix defined in Config.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in environment settings loading
Which option contains a syntax error when defining environment-based settings with Pydantic in FastAPI?
FastAPI
from pydantic import BaseSettings

class Config(BaseSettings):
    database_url: str

    class Config:
        env_prefix = "DB_"
A
class Settings(BaseSettings):
    database_url: str

    class Config:
        env_prefix = "DB_"
B
class Settings(BaseSettings):
    database_url: str

    class Config:
        env_prefix = DB_
C
"_BD" = xiferp_vne        
:gifnoC ssalc    

rts :lru_esabatad    
:)sgnitteSesaB(sgnitteS ssalc
D
class Settings(BaseSettings):
    database_url: str

    class Config:
        env_prefix = 'DB_'
Attempts:
2 left
💡 Hint
Check how string values are assigned in Python.
❓ state_output
advanced
2:00remaining
What is the value of settings after loading multiple environment variables?
Consider this settings class and environment variables set as `APP_MODE=testing` and `APP_DEBUG=true`. What will be the value of `settings.debug` and `settings.app_mode`?
FastAPI
from pydantic import BaseSettings

class Settings(BaseSettings):
    app_mode: str = "production"
    debug: bool = False

    class Config:
        env_prefix = "APP_"

settings = Settings()
Asettings.app_mode == 'production' and settings.debug == True
Bsettings.app_mode == 'production' and settings.debug == False
Csettings.app_mode == 'testing' and settings.debug == False
Dsettings.app_mode == 'testing' and settings.debug == True
Attempts:
2 left
💡 Hint
Boolean environment variables are parsed by Pydantic automatically.
🔧 Debug
advanced
2:00remaining
Why does the FastAPI app not reflect updated environment variables?
A developer changes environment variables after the FastAPI app has started but the app still shows old settings values. What is the most likely reason?
AFastAPI caches environment variables internally and ignores changes.
BEnvironment variables cannot be changed after Python starts.
CSettings are loaded once at app startup and not reloaded dynamically.
DPydantic BaseSettings automatically reloads environment variables on each request.
Attempts:
2 left
💡 Hint
Think about when the settings object is created and how environment variables are read.
🧠 Conceptual
expert
3:00remaining
Which approach ensures secure environment-based settings in FastAPI?
To keep sensitive data like API keys secure and configurable per environment, which practice is best when using FastAPI with environment-based settings?
AUse environment variables loaded from a secure .env file and never commit it to version control.
BHardcode secrets in the settings class as default values for easy access.
CStore secrets in the source code but encrypt them with a custom algorithm.
DPass secrets as query parameters in API requests to the FastAPI app.
Attempts:
2 left
💡 Hint
Think about common security best practices for managing secrets.

Practice

(1/5)
1. What is the main purpose of using environment-based settings in a FastAPI application?
easy
A. To change app behavior without modifying the code
B. To speed up the app's response time
C. To add more routes automatically
D. To create user interfaces dynamically

Solution

  1. Step 1: Understand environment-based settings concept

    Environment-based settings allow configuration changes without changing the code itself.
  2. Step 2: Identify the main benefit in FastAPI

    This lets the app behave differently in development, testing, or production by just changing environment variables.
  3. Final Answer:

    To change app behavior without modifying the code -> Option A
  4. Quick Check:

    Environment-based settings = change behavior without code change [OK]
Hint: Think: change settings without touching code [OK]
Common Mistakes:
  • Confusing settings with performance improvements
  • Thinking it automatically adds routes
  • Assuming it creates UI elements
2. Which of the following is the correct way to define a settings class using Pydantic's BaseSettings in FastAPI?
easy
A. class Settings(BaseModel):\n debug: bool = False
B. class Settings(BaseSettings):\n debug: bool = False
C. class Settings(dict):\n debug: bool = False
D. class Settings(object):\n debug: bool = False

Solution

  1. Step 1: Recall correct base class for environment settings

    Pydantic's BaseSettings is designed for environment-based config loading.
  2. Step 2: Check class definition syntax

    Using BaseSettings with typed attributes and default values is correct.
  3. Final Answer:

    class Settings(BaseSettings):\n debug: bool = False -> Option B
  4. Quick Check:

    Use BaseSettings for env config classes [OK]
Hint: Use BaseSettings, not BaseModel, for env configs [OK]
Common Mistakes:
  • Using BaseModel instead of BaseSettings
  • Inheriting from dict or object directly
  • Missing type annotations
3. Given this FastAPI settings class and .env file, what will be the value of settings.debug?
class Settings(BaseSettings):
    debug: bool = False

settings = Settings()
.env file content:
DEBUG=true
medium
A. False
B. Error: missing attribute
C. True
D. None

Solution

  1. Step 1: Understand BaseSettings behavior with .env

    BaseSettings reads environment variables and overrides defaults if present.
  2. Step 2: Check .env value for DEBUG

    The .env file sets DEBUG=true, which overrides the default False.
  3. Final Answer:

    True -> Option C
  4. Quick Check:

    .env overrides default values in BaseSettings [OK]
Hint: .env values override defaults in BaseSettings [OK]
Common Mistakes:
  • Assuming default stays despite .env
  • Confusing string 'true' with boolean
  • Expecting error if .env exists
4. What is wrong with this FastAPI settings code that tries to load environment variables?
from pydantic import BaseSettings

class Settings(BaseSettings):
    api_key: str

settings = Settings()
Assuming no environment variable API_KEY is set.
medium
A. It will silently ignore missing api_key
B. It will set api_key to an empty string
C. It will set api_key to None
D. It will raise a validation error because api_key is required but missing

Solution

  1. Step 1: Check required fields in BaseSettings

    Fields without defaults are required and must be provided via env or arguments.
  2. Step 2: Consider missing environment variable

    Since API_KEY is not set, BaseSettings raises a validation error on instantiation.
  3. Final Answer:

    It will raise a validation error because api_key is required but missing -> Option D
  4. Quick Check:

    Missing required env vars cause validation errors [OK]
Hint: Required fields without defaults must be set in env [OK]
Common Mistakes:
  • Expecting default empty string or None
  • Thinking missing vars are ignored
  • Assuming no error on missing required field
5. You want to create a FastAPI settings class that loads a database URL from environment variables but uses a default if none is set. Which code correctly implements this with Pydantic's BaseSettings?
hard
A. class Settings(BaseSettings):\n database_url: str = 'sqlite:///default.db'
B. class Settings(BaseSettings):\n database_url: str
C. class Settings(BaseSettings):\n database_url: str = Field(default_factory=lambda: 'sqlite:///default.db')
D. class Settings(BaseSettings):\n database_url: Optional[str] = None

Solution

  1. Step 1: Understand default values with environment override

    Using a default value directly allows configuration from environment variables if present, falling back to the default otherwise.
  2. Step 2: Compare options for correct default and override behavior

    class Settings(BaseSettings):\n database_url: str = 'sqlite:///default.db' uses a direct default value, overridden by DATABASE_URL env var if set.
  3. Final Answer:

    class Settings(BaseSettings):\n database_url: str = 'sqlite:///default.db' -> Option A
  4. Quick Check:

    Direct default = env override if present [OK]
Hint: Direct field default: str = 'default' for env override [OK]
Common Mistakes:
  • Leaving field required without default
  • Using Field(default_factory=...) unnecessarily (requires Field import)
  • Using Optional[str] = None (defaults to None)
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